Identity and Access Management (IAM) decides who may do what to which resource in a cloud account. Almost every large cloud breach on record traces back not to a broken lock but to a grant that was wider than anyone intended, so the discipline of least privilege -- handing out the narrowest permission that still lets the job run -- is the single highest-leverage security practice in the cloud.
The Analogy: The Hospital Credentialing Office
Picture the credentialing office of a large teaching hospital. Everyone who moves through the building -- consultants, nurses, cleaners, visiting researchers, the contractor come to service an MRI -- carries a badge, and every door reads that badge against an access list before its lock releases. The office's entire job is to decide which badge opens which door, and to make sure the pharmacy does not open to a badge that only needs the linen store.
The office issues two very different kinds of badge. A permanent staff badge is tied to a person and never expires on its own; if it is lost, whoever picks it up keeps that access until someone notices and revokes it by hand. A contractor, by contrast, does not get a permanent badge. They present their own driving licence at the desk and are handed a time-boxed badge that stops working at the end of the shift whether or not they remember to return it. That is exactly the difference between a long-lived user credential and an assumed role whose credentials expire on a timer.
Each door's access list is written as tightly as the work allows -- the neurology badge opens neurology, not the drug store -- and a separate "do not admit" flag can be pinned to a sensitive door that refuses every badge, even the department head's, no matter what the allow list says. An explicit refusal always outranks a grant. A master badge that opens every door does exist, for the facilities chief, and it is precisely the badge you least want copied.
The failure that actually befalls such an office is never a picked lock. It is the desk clerk, under pressure to get the MRI contractor working before the morning list, reaching for the facilities master badge and issuing it "just for today" -- on a permanent staff record rather than a time-boxed contractor badge. That evening the contractor's bag is stolen. The badge does not expire, and now the pharmacy, the records room, and every ward stand open to whoever holds it. No door was forced; the breach was authorised in advance by a grant that was both too broad and unable to expire.
Syntax or Core Structure
An IAM policy is a list of statements, each carrying an Effect (Allow or Deny), one or more Actions, and one or more Resources. Evaluating a request means scanning every statement and combining the matches under one fixed rule: an explicit Deny always wins, otherwise a matching Allow grants, and if nothing matches at all the request is denied by default. The model below implements exactly that order of precedence and runs four requests through a two-statement policy.
import fnmatch
def matches(patterns, value):
return any(fnmatch.fnmatch(value, p) for p in patterns)
def as_list(x):
return x if isinstance(x, list) else [x]
def evaluate(policy, action, resource):
decision = 'implicit-deny' # default: nothing matches -> denied
for stmt in policy:
if matches(as_list(stmt['Action']), action) and matches(as_list(stmt['Resource']), resource):
if stmt['Effect'] == 'Deny':
return 'explicit-deny' # a matching Deny wins outright
decision = 'allow'
return decision
POLICY = [
{'Effect': 'Allow', 'Action': ['s3:GetObject', 's3:ListBucket'],
'Resource': ['arn:aws:s3:::app-data', 'arn:aws:s3:::app-data/*']},
{'Effect': 'Deny', 'Action': ['s3:*'],
'Resource': ['arn:aws:s3:::app-data/secrets/*']},
]
REQUESTS = [
('s3:GetObject', 'arn:aws:s3:::app-data/report.csv'),
('s3:GetObject', 'arn:aws:s3:::app-data/secrets/key.pem'),
('s3:DeleteObject', 'arn:aws:s3:::app-data/report.csv'),
('s3:ListBucket', 'arn:aws:s3:::app-data'),
]
for action, resource in REQUESTS:
print('%-15s %-38s -> %s' % (action, resource, evaluate(POLICY, action, resource)))
Output:
s3:GetObject arn:aws:s3:::app-data/report.csv -> allow
s3:GetObject arn:aws:s3:::app-data/secrets/key.pem -> explicit-deny
s3:DeleteObject arn:aws:s3:::app-data/report.csv -> implicit-deny
s3:ListBucket arn:aws:s3:::app-data -> allow
Read the four results in order. The first is a plain read of an ordinary object and is allowed, because it matches the Allow statement and no Deny touches it. The second targets a secret, matches the same Allow but also matches the Deny on app-data/secrets/*, and the Deny wins -- this is how you carve a forbidden hole out of an otherwise-granted prefix. The third asks to delete, an action no statement allows, so it falls through to the default implicit deny; nothing had to say "no" explicitly. The fourth lists the bucket itself and is allowed. The pattern to internalise is the precedence: deny beats allow beats the silent default, and that ordering never depends on the order the statements happen to appear in.
Technical Depth: Users, Roles, and Blast Radius
Two kinds of identity
An IAM user is a long-lived identity whose access keys sit in a config file or an environment variable until someone rotates them. An IAM role is an identity with no permanent credentials at all: a principal trusted to assume it -- an EC2 instance, a Lambda function, a CI job -- is handed short-lived session tokens on demand, and those tokens expire on a timer. The table contrasts the two along the axes that actually matter for security.
| Property | IAM User | IAM Role |
|---|---|---|
| Credential type | Long-lived access keys | Temporary session tokens |
| Typical lifetime | Until manually rotated | 15 minutes to 12 hours |
| Best used for | A few human operators with MFA | Every EC2, Lambda, and CI job |
| If the credential leaks | Valid until someone revokes it | Expires on its own at the TTL |
| How it is obtained | Created once and stored somewhere | Assumed on demand, nothing stored |
The policy the model above encodes
The evaluator in the previous section was not a toy: it is a faithful reading of this real policy document, which grants read access to a data bucket and then carves a Deny hole around its secrets prefix.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadAppData",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::app-data",
"arn:aws:s3:::app-data/*"
]
},
{
"Sid": "DenySecrets",
"Effect": "Deny",
"Action": "s3:*",
"Resource": "arn:aws:s3:::app-data/secrets/*"
}
]
}
Bounding the damage of a leak
Least privilege limits what a stolen credential can touch; short-lived roles limit how long it stays dangerous. The model below quantifies the second axis. It compares a leaked long-lived user key against leaked role credentials with a one-hour TTL, assuming in both cases the leak is noticed a full day later.
def exposure_after_leak(kind, ttl_seconds, detected_after):
if kind == 'user':
return detected_after # permanent key: exposed until a human revokes it
return min(ttl_seconds, detected_after) # role: auto-expires at its TTL regardless
user_exp = exposure_after_leak('user', None, 86400)
role_exp = exposure_after_leak('role', 3600, 86400)
print('user credential leaked, noticed after 86400s: exposed for %ds' % user_exp)
print('role credential leaked, noticed after 86400s: exposed for %ds' % role_exp)
print('role bounds exposure to its TTL: %s' % (role_exp <= 3600))
print('reduction factor: %dx' % (user_exp // role_exp))
Output:
user credential leaked, noticed after 86400s: exposed for 86400s
role credential leaked, noticed after 86400s: exposed for 3600s
role bounds exposure to its TTL: True
reduction factor: 24x
The leaked user key is live for the entire 86400 seconds until a human notices and revokes it, because nothing about a permanent credential expires on its own. The leaked role credentials stop working after 3600 seconds no matter what -- the detection delay is irrelevant, since the tokens time out first. The 24x reduction in exposure window is the whole argument for preferring roles over users for anything automated: you cannot always prevent a leak, but you can make the stolen thing worthless within the hour.
Real World Example: The iam:* Grant That Passed the Linter
A team ships a policy check in CI that fails any pull request whose IAM policy contains a full-admin wildcard -- a statement with "Action": "*". It has caught a few careless grants and everyone trusts it. Then a developer, needing a service to manage its own IAM users, writes "Action": ["iam:*"] with "Resource": ["*"]. It reads as "just IAM permissions, nothing else", it contains no literal * action, so the linter passes it and the policy ships.
The problem is that iam:* includes the actions that grant permissions -- iam:AttachUserPolicy, iam:PutUserPolicy, iam:CreateAccessKey, iam:CreatePolicyVersion -- so any principal holding this policy can attach the AWS-managed AdministratorAccess policy to itself and become a full administrator. It is an admin grant wearing a narrow-looking costume. The model below runs the CI check's logic beside a check that actually evaluates escalation reach.
import fnmatch
def as_list(x):
return x if isinstance(x, list) else [x]
ESCALATION = {'iam:CreateAccessKey', 'iam:AttachUserPolicy', 'iam:PutUserPolicy', 'iam:CreatePolicyVersion'}
ADMIN_POLICY = [
{'Effect': 'Allow', 'Action': ['iam:*'], 'Resource': ['*']}, # scoped to IAM, not a literal "*"
]
def allow_actions(policy):
out = []
for s in policy:
if s['Effect'] == 'Allow':
out.extend(as_list(s['Action']))
return out
def has_literal_star_action(policy):
return '*' in allow_actions(policy)
def reachable_escalation(policy):
pats = allow_actions(policy)
return sorted(e for e in ESCALATION if any(fnmatch.fnmatch(e, p) for p in pats))
reach = reachable_escalation(ADMIN_POLICY)
naive_safe = not has_literal_star_action(ADMIN_POLICY) # "no '*' action -> safe"
correct_safe = (len(reach) == 0) # actually evaluate escalation reach
print('policy contains a literal "*" action: %s' % has_literal_star_action(ADMIN_POLICY))
print('reachable escalation actions (%d): %s' % (len(reach), ', '.join(reach)))
print('naive audit (no literal star -> safe): %s' % naive_safe)
print('correct audit (no escalation reach -> safe): %s' % correct_safe)
print('naive and correct agree: %s' % (naive_safe == correct_safe))
Output:
policy contains a literal "*" action: False
reachable escalation actions (4): iam:AttachUserPolicy, iam:CreateAccessKey, iam:CreatePolicyVersion, iam:PutUserPolicy
naive audit (no literal star -> safe): True
correct audit (no escalation reach -> safe): False
naive and correct agree: False
The two audits disagree, and the disagreement is the finding. The naive check looks only for the literal string * as an action, does not find it, and pronounces the policy safe. The correct check expands iam:* against the set of privilege-escalation actions, finds all four reachable, and pronounces it unsafe -- because a principal that can call iam:AttachUserPolicy on any resource can make itself an administrator, whether or not the word admin ever appears. The four actions print in sorted order precisely so the result is stable to read and to test; iterating the set directly would shuffle them run to run.
The design flaw lives in the checker, not the policy: matching on the literal token * makes the audit blind to every wildcard that is not spelled that exact way, and iam:*, sts:*, and a handful of individual escalation actions all slip through while being just as dangerous. The check is invariant under the thing it exists to catch. The honest version enumerates the actions a policy actually grants -- expanding service wildcards -- and tests that expanded set against a known escalation list, which is roughly what AWS IAM Access Analyzer and tools like Parliament do. Note the model's own limits: the escalation set here is a tiny illustrative sample of a list that runs to dozens of actions, it ignores Conditions that might scope the grant, and it does not follow role-assumption chains where escalation is indirect -- a production analyzer must do all three.
Common Mistakes
- Reaching for
"Action": "*"or"Resource": "*"to make an error go away. A wildcard grant silences the "access denied" message by handing over everything, which is how least privilege dies in practice. Start from zero and add the specific actions and ARNs the workload actually uses; the denied-action name in the error tells you exactly what to add.
- Treating
iam:*as a narrow, IAM-only permission. It includes the actions that grant permissions, so it is a full privilege-escalation path -- the holder can attach an admin policy to itself. Scope IAM permissions to the specific management actions needed, never the service wildcard.
- Using long-lived IAM user access keys for services. An EC2 instance, Lambda, or CI job should assume a role and receive expiring credentials; a hardcoded access key is a permanent backdoor if the repo, image, or laptop it lives on is ever compromised. Reserve users for the few humans who need console access, always with MFA.
- Assuming an Allow somewhere means access is granted. A single matching Deny -- in the identity policy, a resource policy, a permissions boundary, or an SCP -- overrides every Allow. When a request is unexpectedly denied, look for the Deny before adding more Allows, which will not help.
- Forgetting the implicit default deny. If no statement matches, the request is denied even though nothing said "no". Adding an unrelated Allow does not fix a missing permission; you must grant the exact action and resource that the request names.
- Confusing authentication with authorization. Being a valid, signed-in principal (authentication) says nothing about whether you may perform an action (authorization). A leaked-but-valid credential is denied everything its policies do not grant, which is exactly why least privilege contains the blast radius.
- Auditing policies by grepping for the literal
*. As the Real World Example shows, dangerous grants likeiam:*contain no literal full-wildcard action and sail past a naive check. Evaluate the actions a policy actually grants against a known-dangerous list instead of pattern-matching the text.
- Never rotating or reviewing credentials. Access keys that are years old, and roles whose policies accreted permissions no one removed, are the normal state of a neglected account. Generate a credential report regularly, disable keys older than your rotation window, and prune unused permissions.
- Over-scoping a role's trust policy. A role is only as safe as the set of principals allowed to assume it; a trust policy that trusts an entire account, or
"Principal": "*", lets far more than the intended service take on the role's permissions. Trust the narrowest specific principal or service that needs it.
Best Practices
- Start every policy from zero and add only the actions and resources the workload names. Least privilege is a floor you build up to, not a ceiling you trim down from; grant
s3:GetObjecton one bucket, nots3:*on*.
- Prefer roles over users for everything automated. Attach roles to EC2, Lambda, ECS tasks, and CI providers via OIDC so code receives expiring credentials and never stores a long-lived key.
- Scope resources with ARNs and tighten with Conditions. Name the exact bucket, table, or queue, and add Conditions such as source IP, VPC, or MFA-present so a matching action still fails outside the intended context.
- Use an explicit Deny to carve forbidden holes out of broad Allows. A Deny on a secrets prefix or a production tag protects the sensitive subset even when a wider Allow exists, and it cannot be overridden by any Allow.
- Set permissions boundaries and SCPs as guardrails. Let teams create their own roles freely, but cap the maximum permissions any role can have so a mistake cannot exceed the boundary the organization set.
- Rotate, report, and prune on a schedule. Generate a credential report, disable keys past your rotation window, and remove permissions that access-analyzer or last-used data shows are never exercised.
- Require MFA for human users and sensitive actions. Console access and privileged operations should demand a second factor via an
aws:MultiFactorAuthPresentcondition, so a leaked password alone is not enough.
- Audit policies by evaluated reach, not by text matching. Expand service wildcards and test the resulting action set against a known escalation list; run IAM Access Analyzer to surface external access and unused grants before they become incidents.
Practice Exercises
- Extend the evaluator with a resource policy. Add a second policy list to the Syntax model representing an S3 bucket policy, and change
evaluateto deny unless both the identity policy and the resource policy allow, while still letting either one's Deny win. Confirm a request allowed by identity but absent from the bucket policy now falls to implicit deny.
- Quantify a shorter TTL. Using the blast-radius model, compute the exposure window and reduction factor for role TTLs of 900, 3600, and 43200 seconds against a leak noticed after 86400 seconds. Show that the reduction factor is exactly
86400 // ttland explain the security-versus-convenience trade-off of a very short TTL.
- Break the naive linter three ways. Write three distinct policies that grant privilege escalation without containing a literal
*action (for example viaiam:*, viasts:*, and via a single escalation action on*), and show thathas_literal_star_actionreturns False whilereachable_escalationreturns a non-empty list for each.
- Design a least-privilege role for a backup job. Write the trust policy (which service may assume it) and the permission policy (read the source bucket, write the backup bucket, nothing else) for a nightly backup Lambda, then list the exact requests it should be able to make and one plausible request it must be denied.