Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 2

Cloud IAM: Policies, Roles and Escalation Paths

Build a small evaluator of AWS IAM policy logic, use it to understand explicit deny, default deny, wildcards and conditions, then audit shipped policies and a credential report for wildcard grants, old access keys, broad cross-account trust and escalation permission combinations, and fix them with least privilege and a pinned GitHub OIDC trust policy.

Contentsand lesson path

What you will learn

  • Find and fix cloud IAM risks (wildcard policies, long-lived access keys, overly broad cross-account trust, privilege escalation paths) using least-privilege policies and workload identity.

Prerequisites: Cloud Basics

01. The problem

A shop runs in one AWS account. Over a year its IAM (identity and access management) grew by hand: a developer policy, a continuous-integration (CI) user with a stored access key, a data team that builds serverless functions, and a helper role. Your task is to review the account from exported files and find the access an attacker would want.

You first build a small evaluator of how AWS reads a policy, then audit the policies and credential report, and finally fix the worst problem: a CI user with a long-lived key and far too many rights. It runs locally with Python 3.12. Put each file below in a folder called iam-review.

02. Step 1: Model the evaluation rules

AWS decides a request in a fixed order. Everything starts as an implicit deny: if no statement allows the action, the answer is deny. Any statement that allows it flips the result to allow. But one matching explicit deny, a statement with "Effect": "Deny", overrides every allow. A statement matches when its Action matches the operation, its Resource matches the target, and any Condition holds. Action names use * and ? as wildcards and ignore case; resource ARNs (Amazon Resource Names) are matched case-sensitively. If a condition key is missing from the request, a normal operator such as StringEquals is false, but a negated one such as StringNotEquals is true. The evaluator below models identity policies for one account. It is a teaching model, not the real engine. It leaves out resource-based policies, which can also grant access (a bucket policy can allow a request that no identity policy allows), and the policy types that can only limit permissions: permissions boundaries, SCPs, resource control policies (RCPs) and session policies.

Python · iam-review/iam_eval.py
"""A small model of AWS IAM evaluation for identity policies in one account."""
import fnmatch


def as_list(value):
    return value if isinstance(value, list) else [value]


def wild(pattern, value, case):
    if not case:
        pattern, value = pattern.lower(), value.lower()
    pattern = pattern.replace("[", "[[]")        # IAM has no [...] classes
    return fnmatch.fnmatchcase(value, pattern)   # * and ? as in IAM


def matches(stmt, action, resource):
    if "Action" in stmt:
        ok = any(wild(p, action, False) for p in as_list(stmt["Action"]))
    else:
        ok = not any(wild(p, action, False) for p in as_list(stmt["NotAction"]))
    return ok and any(wild(p, resource, True) for p in as_list(stmt["Resource"]))


def condition_holds(cond, ctx):
    for op, keys in cond.items():              # operators: AND
        for key, wanted in keys.items():       # keys: AND
            have = ctx.get(key)
            if op == "Bool":
                ok = have is not None and str(have).lower() in (
                    str(w).lower() for w in as_list(wanted))
            elif op in ("StringEquals", "StringLike"):
                ok = have is not None and any(   # values: OR
                    have == w if op == "StringEquals" else wild(w, have, True)
                    for w in as_list(wanted))
            elif op == "StringNotEquals":
                ok = have is None or have not in as_list(wanted)
            else:
                raise ValueError(f"operator {op} not modelled")
            if not ok:
                return False
    return True


def evaluate(policies, action, resource, ctx=None):
    ctx = ctx or {}
    allowed = False
    for policy in policies:
        for stmt in as_list(policy["Statement"]):
            if not matches(stmt, action, resource):
                continue
            if not condition_holds(stmt.get("Condition", {}), ctx):
                continue
            if stmt["Effect"] == "Deny":
                return "explicit deny"
            allowed = True
    return "allow" if allowed else "implicit deny"

Save this developer policy as policies/developer.json. It allows full access to one bucket, denies deleting any bucket, allows read-only EC2 calls, and allows stopping an instance only with MFA.

JSON · iam-review/policies/developer.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Sid": "OwnBucket", "Effect": "Allow", "Action": "s3:*",
     "Resource": ["arn:aws:s3:::shop-dev-assets", "arn:aws:s3:::shop-dev-assets/*"]},
    {"Sid": "NoBucketDelete", "Effect": "Deny", "Action": "s3:DeleteBucket",
     "Resource": "*"},
    {"Sid": "ReadEc2", "Effect": "Allow", "Action": "ec2:Describe*", "Resource": "*"},
    {"Sid": "StopWithMfa", "Effect": "Allow", "Action": "ec2:StopInstances",
     "Resource": "*", "Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}}
  ]
}

The test file checks each rule, including the cases that must be denied: a security evaluator is only trustworthy once you have shown what it refuses.

Python · iam-review/test_eval.py
"""Checks iam_eval.py against the documented IAM rules, including negative cases."""
import json

from iam_eval import evaluate

dev = [json.load(open("policies/developer.json"))]
# A guardrail: deny every action to callers outside organisation o-exampleorg.
org = [{"Statement": [
    {"Effect": "Allow", "Action": "s3:*", "Resource": "*"},
    {"Effect": "Deny", "Action": "*", "Resource": "*", "Condition":
     {"StringNotEquals": {"aws:PrincipalOrgID": "o-exampleorg"}}}]}]
B = "arn:aws:s3:::shop-dev-assets"
CASES = [  # policies, action, resource, context, expected, rule being tested
    (dev, "s3:PutObject", B + "/logo.png", {}, "allow", "wildcard action s3:*"),
    (dev, "s3:DeleteBucket", B, {}, "explicit deny", "Deny beats the s3:* Allow"),
    (dev, "s3:GetObject", "arn:aws:s3:::shop-prod-data/x", {}, "implicit deny",
     "no statement matches: default deny"),
    (dev, "EC2:describeInstances", "*", {}, "allow", "action names ignore case"),
    (dev, "s3:GetObject", "arn:aws:s3:::Shop-Dev-Assets/x", {}, "implicit deny",
     "resource ARNs are case-sensitive"),
    (dev, "ec2:StopInstances", "*", {}, "implicit deny", "condition key missing"),
    (dev, "ec2:StopInstances", "*", {"aws:MultiFactorAuthPresent": "true"}, "allow",
     "condition met"),
    (org, "s3:GetObject", B + "/x", {"aws:PrincipalOrgID": "o-exampleorg"}, "allow",
     "StringNotEquals, key matches"),
    (org, "s3:GetObject", B + "/x", {}, "explicit deny",
     "StringNotEquals, key missing"),
]
failed = 0
for policies, action, resource, ctx, want, rule in CASES:
    got = evaluate(policies, action, resource, ctx)
    failed += got != want
    print(f"{'PASS' if got == want else 'FAIL'}  {action:22} {got:13} {rule}")
print("failed:", failed)
raise SystemExit(1 if failed else 0)
Terminal
mkdir -p iam-review && cd iam-review   # put the files below here
python3 test_eval.py
Expected output
PASS  s3:PutObject           allow         wildcard action s3:*
PASS  s3:DeleteBucket        explicit deny Deny beats the s3:* Allow
PASS  s3:GetObject           implicit deny no statement matches: default deny
PASS  EC2:describeInstances  allow         action names ignore case
PASS  s3:GetObject           implicit deny resource ARNs are case-sensitive
PASS  ec2:StopInstances      implicit deny condition key missing
PASS  ec2:StopInstances      allow         condition met
PASS  s3:GetObject           allow         StringNotEquals, key matches
PASS  s3:GetObject           explicit deny StringNotEquals, key missing
failed: 0

s3:DeleteBucket is covered by the wildcard allow s3:*, but the explicit Deny wins. A read on a production bucket matches no statement, so it is implicit deny. The case-sensitivity row shows why a typo in an ARN silently fails. The ec2:StopInstances rows show a condition changing the outcome, and the last row is the negated case: with no aws:PrincipalOrgID in the request, StringNotEquals is true, so the guardrail's Deny applies.

03. Step 2: Read the credential report

AWS can produce a credential report: one CSV row per IAM user plus the root user, listing password and access-key status. The columns are fixed; the audit uses mfa_active, password_enabled, each access_key_N_active and each access_key_N_last_rotated. The root user appears as the literal name <root_account>. A long-lived access key (a static credential pair for API calls) does not expire, so if it leaks it works until someone disables it. The generator below writes one in the real column order.

Python · iam-review/make_report.py
"""Writes credential-report.csv with the columns of a real IAM credential report."""
import csv

COLUMNS = ("user arn user_creation_time password_enabled password_last_used "
           "password_last_changed password_next_rotation mfa_active "
           "access_key_1_active access_key_1_last_rotated access_key_1_last_used_date "
           "access_key_1_last_used_region access_key_1_last_used_service "
           "access_key_2_active access_key_2_last_rotated access_key_2_last_used_date "
           "access_key_2_last_used_region access_key_2_last_used_service "
           "cert_1_active cert_1_last_rotated cert_2_active cert_2_last_rotated "
           "additional_credentials_info").split()
ACCT = "arn:aws:iam::111122223333:"
USERS = [
    {"user": "<root_account>", "arn": ACCT + "root", "password_enabled": "true",
     "password_last_used": "2026-02-11T08:15:00+00:00", "mfa_active": "true",
     "password_last_changed": "not_supported",
     "password_next_rotation": "not_supported"},
    {"user": "ana", "password_enabled": "true", "mfa_active": "true",
     "password_last_used": "2026-11-14T07:40:00+00:00"},
    {"user": "bob", "password_enabled": "true", "mfa_active": "false",
     "password_last_used": "2026-11-12T16:02:00+00:00"},
    {"user": "ci-deploy", "access_key_1_active": "true",
     "access_key_1_last_rotated": "2023-02-14T11:05:00+00:00",
     "access_key_1_last_used_date": "2026-11-15T23:10:00+00:00",
     "access_key_1_last_used_region": "eu-west-1",
     "access_key_1_last_used_service": "cloudformation"},
    {"user": "old-batch", "access_key_1_active": "true",
     "access_key_1_last_rotated": "2022-08-01T12:10:00+00:00",
     "access_key_1_last_used_date": "2025-03-30T02:00:00+00:00",
     "access_key_1_last_used_region": "eu-west-1",
     "access_key_1_last_used_service": "s3", "access_key_2_active": "true",
     "access_key_2_last_rotated": "2024-01-09T10:00:00+00:00"},
]
with open("credential-report.csv", "w", newline="") as fh:
    out = csv.DictWriter(fh, COLUMNS)
    out.writeheader()
    for row in USERS:
        full = {c: "N/A" for c in COLUMNS}
        full.update({c: "false" for c in COLUMNS if c.endswith("_active")
                     or c in ("password_enabled", "mfa_active")})
        full.update(additional_credentials_info="", arn=ACCT + "user/" + row["user"],
                    user_creation_time="2024-01-02T09:00:00+00:00")
        full.update(row)
        out.writerow(full)
print(len(USERS), "users written to credential-report.csv")
Terminal
python3 make_report.py
Expected output
5 users written to credential-report.csv

The five principals: root (MFA, no key), ana (MFA), bob (no MFA), ci-deploy (one key) and old-batch (two old keys).

04. Step 3: Audit the policies and report

Save the four identity policies and two trust policies below, then run the audit. A trust policy is the resource-based policy on a role that says which principals (Principal) may assume it. In order: a CI user allowed to do everything, a data team with iam:PassRole plus the right to create and invoke functions, a platform helper with several IAM write permissions, a role that trusts any AWS account, and a role that trusts a whole vendor account with no condition.

JSON · iam-review/policies/ci-deployer.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Sid": "Everything", "Effect": "Allow", "Action": "*", "Resource": "*"}
  ]
}
JSON · iam-review/policies/data-team.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Sid": "Functions", "Effect": "Allow",
     "Action": ["lambda:CreateFunction", "lambda:InvokeFunction",
                "lambda:GetFunction"],
     "Resource": "*"},
    {"Sid": "PassAnyRole", "Effect": "Allow", "Action": "iam:PassRole",
     "Resource": "*"},
    {"Sid": "ReadData", "Effect": "Allow", "Action": ["s3:GetObject", "s3:ListBucket"],
     "Resource": ["arn:aws:s3:::shop-analytics", "arn:aws:s3:::shop-analytics/*"]}
  ]
}
JSON · iam-review/policies/platform-helper.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Sid": "ManagePolicies", "Effect": "Allow",
     "Action": ["iam:CreatePolicyVersion", "iam:GetPolicy", "iam:ListPolicies"],
     "Resource": "*"},
    {"Sid": "HelpUsers", "Effect": "Allow",
     "Action": ["iam:AttachUserPolicy", "iam:CreateAccessKey"],
     "Resource": "arn:aws:iam::111122223333:user/*"},
    {"Sid": "FixTrust", "Effect": "Allow",
     "Action": ["iam:UpdateAssumeRolePolicy", "sts:AssumeRole"],
     "Resource": "arn:aws:iam::111122223333:role/*"}
  ]
}
JSON · iam-review/policies/trust-reporting.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "sts:AssumeRole"}
  ]
}
JSON · iam-review/policies/trust-vendor.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::444455556666:root"},
     "Action": "sts:AssumeRole"}
  ]
}

The audit reports wildcard grants, old keys, console passwords without MFA, over-broad trust and known escalation permission combinations, with high-severity findings first. Files whose names start with trust- are read as trust policies.

Python · iam-review/audit.py
"""Finds IAM risks in the shipped policies and credential report. Detection only."""
import csv
import glob
import json
import os
import textwrap
from datetime import datetime, timezone

TODAY = datetime(2026, 11, 16, tzinfo=timezone.utc)
KEY_MAX_AGE_DAYS = 90
# Permission sets that together let a principal gain more rights. Sources in the lesson.
ESCALATION = [
    ({"iam:passrole", "lambda:createfunction", "lambda:invokefunction"},
     "pass a role to a new function, then invoke it to run with that role"),
    ({"iam:createpolicyversion"},
     "create a new default version of a policy to grant itself any action"),
    ({"iam:attachuserpolicy"},
     "attach an administrator policy to its own user"),
    ({"iam:updateassumerolepolicy", "sts:assumerole"},
     "rewrite a role's trust policy, then assume that role"),
]


def actions_of(policy):
    out = set()
    for stmt in policy["Statement"]:
        if stmt["Effect"] != "Allow" or "Action" not in stmt:
            continue
        raw = stmt["Action"]
        for a in raw if isinstance(raw, list) else [raw]:
            out.add(a.lower())
    return out


def is_wild(action):
    return action == "*" or action.endswith(":*") or action == "iam:*"


def audit_policy(name, policy):
    findings = []
    acts = actions_of(policy)
    for stmt in policy["Statement"]:
        if stmt.get("Effect") == "Allow" and "Action" in stmt:
            act = stmt["Action"]
            raw = act if isinstance(act, list) else [act]
            if any(is_wild(a) for a in raw):
                res = stmt.get("Resource", "")
                star = res == "*" or (isinstance(res, list) and "*" in res)
                findings.append(("HIGH" if star else "MEDIUM", name,
                                 f"wildcard action {raw} on resource {res!r}"))
    for combo, why in ESCALATION:
        if combo <= acts:
            findings.append(("HIGH", name,
                             f"escalation: {sorted(combo)} lets the holder {why}"))
    return findings


def audit_trust(name, policy):
    findings = []
    for stmt in policy["Statement"]:
        principal = stmt.get("Principal", {})
        aws = principal.get("AWS") if isinstance(principal, dict) else principal
        cond = stmt.get("Condition", {})
        if aws == "*" and not cond:
            findings.append(("HIGH", name,
                             "trusts any AWS principal with no condition"))
        elif isinstance(aws, str) and aws.endswith(":root") and not cond:
            findings.append(("MEDIUM", name,
                             f"trusts a whole account ({aws}) with no ExternalId"))
    return findings


def audit_report(path):
    findings = []
    for row in csv.DictReader(open(path)):
        user = row["user"]
        if user == "<root_account>":
            if "true" in (row["access_key_1_active"], row["access_key_2_active"]):
                findings.append(("HIGH", user, "root user has an active access key"))
            if row["mfa_active"] != "true":
                findings.append(("HIGH", user, "root user has no MFA"))
        if (row["password_enabled"] == "true" and row["mfa_active"] == "false"
                and user != "<root_account>"):
            findings.append(("HIGH", user, "console password without MFA"))
        for n in ("1", "2"):
            if row[f"access_key_{n}_active"] != "true":
                continue
            rotated = row[f"access_key_{n}_last_rotated"]
            if rotated in ("N/A", ""):
                continue
            age = (TODAY - datetime.fromisoformat(rotated)).days
            if age > KEY_MAX_AGE_DAYS:
                findings.append(("MEDIUM", user,
                                 f"access key {n} is {age} days old "
                                 f"(limit {KEY_MAX_AGE_DAYS})"))
    return findings


def main():
    here = os.path.dirname(os.path.abspath(__file__))
    findings = []
    for path in sorted(glob.glob(os.path.join(here, "policies", "*.json"))):
        name = os.path.basename(path)
        policy = json.load(open(path))
        fn = audit_trust if name.startswith("trust-") else audit_policy
        findings += fn(name, policy)
    findings += audit_report(os.path.join(here, "credential-report.csv"))
    order = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
    for sev, who, detail in sorted(findings, key=lambda f: (order[f[0]], f[1])):
        head = f"{sev:6} {who:20} "
        lines = textwrap.wrap(detail, width=88 - len(head)) or [""]
        print(head + lines[0])
        for extra in lines[1:]:
            print(" " * len(head) + extra)
    print(f"total findings: {len(findings)}")


if __name__ == "__main__":
    main()
Terminal
python3 audit.py
Expected output
HIGH   bob                  console password without MFA
HIGH   ci-deployer.json     wildcard action ['*'] on resource '*'
HIGH   data-team.json       escalation: ['iam:passrole', 'lambda:createfunction',
                            'lambda:invokefunction'] lets the holder pass a role to a
                            new function, then invoke it to run with that role
HIGH   platform-helper.json escalation: ['iam:createpolicyversion'] lets the holder
                            create a new default version of a policy to grant itself any
                            action
HIGH   platform-helper.json escalation: ['iam:attachuserpolicy'] lets the holder attach
                            an administrator policy to its own user
HIGH   platform-helper.json escalation: ['iam:updateassumerolepolicy', 'sts:assumerole']
                            lets the holder rewrite a role's trust policy, then assume
                            that role
HIGH   trust-reporting.json trusts any AWS principal with no condition
MEDIUM ci-deploy            access key 1 is 1370 days old (limit 90)
MEDIUM developer.json       wildcard action ['s3:*'] on resource ['arn:aws:s3:::shop-
                            dev-assets', 'arn:aws:s3:::shop-dev-assets/*']
MEDIUM old-batch            access key 1 is 1567 days old (limit 90)
MEDIUM old-batch            access key 2 is 1041 days old (limit 90)
MEDIUM trust-vendor.json    trusts a whole account (arn:aws:iam::444455556666:root) with
                            no ExternalId
total findings: 12

Four findings need a word on why they are escalation paths, not just broad access: each lets a principal who is not an administrator become one. Rhino Security Labs' study of AWS escalation methods documents them.

  • iam:PassRole with lambda:CreateFunction and lambda:InvokeFunction: PassRole grants nothing on its own; it lets the holder hand an existing role to a service. With a function they create and run, their code gets that role's rights.
  • iam:CreatePolicyVersion: the holder adds a new default version to a policy they can reach (one API flag does both), rewriting their own permissions to anything.
  • iam:AttachUserPolicy: the holder attaches the AWS-managed AdministratorAccess policy to their own user.
  • iam:UpdateAssumeRolePolicy with sts:AssumeRole: the holder rewrites a role's trust policy to trust themselves, then assumes it.

The trust findings are about reach. A trust policy with "Principal": {"AWS": "*"} and no condition lets any principal in any AWS account assume the role; the caller's account must allow sts:AssumeRole, but an attacker controls that. Trusting a whole account (:root) is narrower, but any principal there whose own policies allow sts:AssumeRole can use the role. For a third party, add an sts:ExternalId condition: a unique ID the vendor generates for each customer and sends when it assumes the role. It is not a secret. It stops the vendor being tricked into using your role for another customer (the confused-deputy problem).

05. Step 4: Fix the CI user with least privilege and OIDC

The CI user has two problems: a wildcard policy and a stored key 1370 days old. First, replace Action: "*" with only the actions the pipeline needs: upload the website to one bucket and invalidate one CloudFront distribution. Least privilege means naming the exact actions and resources.

JSON · iam-review/fixed/ci-deployer.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Sid": "PushWebsite", "Effect": "Allow",
     "Action": ["s3:PutObject", "s3:GetObject", "s3:ListBucket"],
     "Resource": ["arn:aws:s3:::shop-prod-site", "arn:aws:s3:::shop-prod-site/*"]},
    {"Sid": "Invalidate", "Effect": "Allow",
     "Action": "cloudfront:CreateInvalidation",
     "Resource": "arn:aws:cloudfront::111122223333:distribution/E1111EXAMPLE"}
  ]
}

Second, remove the stored key entirely. GitHub Actions can authenticate to AWS with workload identity federation using OpenID Connect (OIDC): the workflow presents a short-lived signed token (a JWT) that AWS exchanges for temporary credentials, so there is no key to leak. The role's trust policy pins who may use it with two conditions: the audience aud must equal sts.amazonaws.com, and the subject sub must match your repository and a branch or environment. IAM refuses to save a GitHub trust policy whose sub is missing or only wildcards.

Copy the sub format your repository really uses. Repositories created before 15 July 2026 use names only, unless the owner opted in to the new format: repo:ORG/REPO:ref:refs/heads/BRANCH. Repositories created after that date, and ones renamed or transferred since, use GitHub's immutable format, which adds the owner and repository IDs so that a recycled name cannot reproduce the subject: repo:ORG@OWNER-ID/REPO@REPO-ID:ref:refs/heads/BRANCH. The IDs are the token's repository_owner_id and repository_id claims; gh api repos/ORG/REPO --jq '.owner.id, .id' prints them. The fixed policy pins main of a repository created in November 2026.

JSON · iam-review/fixed/ci-trust.json
{
  "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:example-org@1234567/shop-site@7654321:ref:refs/heads/main"}}}
  ]
}

A tempting shortcut is to allow the whole organisation with a wildcard sub, saved as policies/trust-github-wide.json. Any repository in the organisation could then assume the role, including a new one made by anyone with the right to create repositories there. The checker below rejects a sub that is only wildcards, ends in :* or /*, or fits neither GitHub format (that role could never be assumed), and names the format of a pinned one. Run it on both.

JSON · iam-review/policies/trust-github-wide.json
{
  "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"},
       "StringLike": {"token.actions.githubusercontent.com:sub":
         "repo:example-org@1234567/*"}}}
  ]
}
Python · iam-review/oidc_check.py
"""Rejects a GitHub Actions OIDC trust policy that is too broad. Checks only."""
import json
import re
import sys

PROVIDER = "token.actions.githubusercontent.com"
# repo:OWNER[@OWNER-ID]/REPO[@REPO-ID]: then a ref, an environment or pull_request
SUB = re.compile(r"repo:[^/:@]+(@\d+)?/[^/:@]+(@\d+)?:"
                 r"(ref:refs/(heads|tags)/.+|environment:.+|pull_request)")


def check_trust(policy):
    problems, formats = [], []
    for stmt in policy["Statement"]:
        if stmt.get("Action") != "sts:AssumeRoleWithWebIdentity":
            continue
        fed = stmt.get("Principal", {}).get("Federated", "")
        if PROVIDER not in fed:
            continue
        cond = stmt.get("Condition", {})
        values = {}
        for op in ("StringEquals", "StringLike"):
            values.update({(op, k): v for k, v in cond.get(op, {}).items()})
        aud = next((v for (op, k), v in values.items() if k.endswith(":aud")), None)
        if aud != "sts.amazonaws.com":
            problems.append(f"aud must equal 'sts.amazonaws.com', found {aud!r}")
        subs = [(op, v) for (op, k), v in values.items() if k.endswith(":sub")]
        if not subs:
            problems.append("no :sub condition: any repository could assume the role")
        for op, sub in subs:
            if set(sub) <= {"*", "?"}:
                problems.append(f"sub {sub!r} is only wildcards: it pins nothing")
            elif op == "StringLike" and (sub.endswith(":*") or sub.endswith("/*")):
                problems.append(f"sub {sub!r} allows a whole org or repo, not a branch")
            elif not SUB.fullmatch(sub):
                problems.append(f"sub {sub!r} matches no GitHub subject format")
            else:
                ids = "@" in sub.split(":")[1]
                formats.append("immutable ID format" if ids else "name-only format")
    return problems, formats


if __name__ == "__main__":
    problems, formats = check_trust(json.load(open(sys.argv[1])))
    for p in problems:
        print("REJECT", p)
    if not problems:
        print(f"OK: sub pins one repository and ref ({', '.join(formats)})")
    sys.exit(1 if problems else 0)
Terminal
python3 oidc_check.py fixed/ci-trust.json
python3 oidc_check.py policies/trust-github-wide.json
Expected output
OK: sub pins one repository and ref (immutable ID format)
REJECT sub 'repo:example-org@1234567/*' allows a whole org or repo, not a branch

Confirm the fix with the evaluator from step 1.

Terminal
python3 -c '
import json; from iam_eval import evaluate
p = [json.load(open("fixed/ci-deployer.json"))]
print(evaluate(p, "iam:AttachUserPolicy", "arn:aws:iam::111122223333:user/ci-deploy"))
print(evaluate(p, "s3:PutObject", "arn:aws:s3:::shop-prod-site/index.html"))'
Expected output
implicit deny
allow

The admin path is gone and the pipeline still works. Azure also matches the subject of a federated credential; Google Cloud uses attribute conditions on mapped claims such as the repository owner or ID.

06. Common mistakes

07. Check your understanding

Practice check · 3 questions

Reading the audit

Three questions about the evaluator and the findings.

Q1. A user has the developer policy plus a second policy allowing `s3:DeleteBucket` on `*`. What does the evaluator return for `s3:DeleteBucket` on the dev bucket, and why?
Q2. You add a policy granting only `iam:CreatePolicyVersion` and run `audit.py`. What does it report for that policy, and why?
Q3. A GitHub OIDC trust policy sets `aud` to `sts.amazonaws.com` and `sub` to `repo:acme@1234/*`. Why does `oidc_check.py` reject it?
Practice only: not graded, not saved, not evidence.

08. Apply it

For the skill project, turn the audit into something you can hand to the account owner:

  • Add one more escalation combination to ESCALATION (for example iam:CreateAccessKey on another user), a policy that triggers it, and a source.
  • Run oidc_check.py on a trust policy that uses the real sub of one of your repositories.
  • Write a least-privilege data-team policy that still reads shop-analytics but cannot pass an arbitrary role, and confirm it with the evaluator.
  • Produce a short report: each finding, its severity, the fix, and whether the fix is deployed or still open.

09. Review prompt

Without looking back, explain: how AWS decides a request and why an explicit deny wins; how a missing key affects a negated condition; why a long-lived access key is a risk and what replaces it; two escalation permission combinations and why each is a path; what makes a cross-account trust policy too broad and how to narrow it; and the two conditions a GitHub OIDC trust policy must pin, in the sub format your repository uses.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check