Writing an AWS-Style Policy Evaluator
To review IAM you need to answer "is this request allowed?" faster and more reliably than by reading JSON by eye. Attackers who obtain a key ask the same question, by trial and error against the live API; auditors should answer it offline, from the policies. IAM Policies built a first evaluator for one identity policy. This lesson writes the version an auditor needs: identity and resource policies, NotAction and NotResource, condition operators including the negated ones, and the rule that makes cross-account access different from same-account access. The next lessons add boundaries and SCPs and use it to hunt for over-broad grants.
The model follows AWS's published evaluation logic for a single account and a resource policy; it is a teaching model, not AWS's code, and real IAM has more condition operators, policy variables and service-specific rules.
The rules being modelled
- Collect every applicable statement: identity policies of the caller, plus the resource's policy (bucket policy, key policy, role trust policy…).
- If any applicable statement is a
Deny, the answer is deny. An explicit deny always wins. - Otherwise look for an
Allow. In the same account, an allow in either the identity policy or the resource policy is enough (with one subtlety below). Across accounts, both sides must allow: the resource's account in its resource policy, the caller's account in the caller's identity policy. - No allow means implicit deny.
A statement applies when its action matches (Action, or not listed in NotAction), its resource matches (Resource or NotResource), for a resource policy its Principal matches the caller, and every condition is true. Inside a condition block, different operators and keys are ANDed; multiple values for one key are ORed. When a key is missing from the request, ordinary operators are false and negated ones (StringNotEquals, NotIpAddress) are true; …IfExists variants are true.
The subtlety: a resource policy that names a whole account (arn:aws:iam::123456789012:root) doesn't grant anything by itself; it delegates to that account's identity policies. Naming a specific role or user, or "*", grants directly.
The evaluator
import ipaddress
from fnmatch import fnmatchcase
def as_list(x):
return x if isinstance(x, list) else [x]
def any_match(patterns, value, case_insensitive=False):
if case_insensitive:
return any(fnmatchcase(value.lower(), p.lower()) for p in as_list(patterns))
return any(fnmatchcase(value, p) for p in as_list(patterns))
POSITIVE = {
"StringEquals": lambda a, e: a == e,
"StringLike": lambda a, e: fnmatchcase(a, e),
"ArnLike": lambda a, e: fnmatchcase(a, e),
"Bool": lambda a, e: str(a).lower() == str(e).lower(),
"IpAddress": lambda a, e: ipaddress.ip_address(a) in ipaddress.ip_network(e),
"NumericLessThan": lambda a, e: float(a) < float(e),
}
NEGATED = {"StringNotEquals": "StringEquals", "StringNotLike": "StringLike", "NotIpAddress": "IpAddress"}
def conditions_hold(cond, ctx):
for op, tests in (cond or {}).items():
if_exists = op.endswith("IfExists")
op = op.removesuffix("IfExists")
for key, expected in tests.items():
if key not in ctx:
if if_exists or op in NEGATED:
continue
return False
if op in NEGATED:
if any(POSITIVE[NEGATED[op]](ctx[key], e) for e in as_list(expected)):
return False
elif not any(POSITIVE[op](ctx[key], e) for e in as_list(expected)):
return False
return True
def principal_match(st, caller):
p = st.get("Principal")
if p == "*" or p == {"AWS": "*"}:
return "direct"
for arn in as_list(p["AWS"]):
if arn == caller:
return "direct"
if arn == f"arn:aws:iam::{caller.split(':')[4]}:root":
return "account" # delegates to the caller account's identity policies
return None
def applies(st, req):
act_ok = (any_match(st["Action"], req["action"], True) if "Action" in st
else not any_match(st["NotAction"], req["action"], True))
res_ok = (any_match(st["Resource"], req["resource"]) if "Resource" in st
else not any_match(st["NotResource"], req["resource"]))
return act_ok and res_ok and conditions_hold(st.get("Condition"), req["ctx"])
def evaluate(req, identity_policies, resource_policy=None):
caller_acct = req["caller"].split(":")[4]
id_allow = res_allow = None
for pol in identity_policies:
for st in pol["Statement"]:
if applies(st, req):
if st["Effect"] == "Deny":
return f"DENY explicit ({st.get('Sid', '?')})"
id_allow = id_allow or st.get("Sid", "?")
for st in (resource_policy or {"Statement": []})["Statement"]:
kind = principal_match(st, req["caller"])
if kind and applies(st, req):
if st["Effect"] == "Deny":
return f"DENY explicit (resource: {st.get('Sid', '?')})"
if kind == "direct" or caller_acct != req["resource_account"]:
res_allow = res_allow or st.get("Sid", "?")
if caller_acct == req["resource_account"]:
if id_allow or res_allow:
return f"ALLOW (identity: {id_allow}, resource: {res_allow})"
return "DENY implicit"
if id_allow and res_allow:
return f"ALLOW cross-account (identity: {id_allow}, resource: {res_allow})"
return "DENY implicit (cross-account needs both sides)"
# --- the lab account ---------------------------------------------------------
ACCT, VENDOR = "123456789012", "999988887777"
BUCKET = "arn:aws:s3:::lab-app-uploads"
identity = {
f"arn:aws:iam::{ACCT}:user/alice": [{"Statement": [
{"Sid": "ReadUploads", "Effect": "Allow", "Action": ["s3:Get*", "s3:ListBucket"], "Resource": [BUCKET, BUCKET + "/*"]},
{"Sid": "DeleteWithMfa", "Effect": "Allow", "Action": "s3:DeleteObject", "Resource": BUCKET + "/*",
"Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}}]}],
f"arn:aws:iam::{ACCT}:user/bob": [{"Statement": [
{"Sid": "AllButIam", "Effect": "Allow", "NotAction": "iam:*", "Resource": "*"}]}],
f"arn:aws:iam::{ACCT}:role/app-role": [],
f"arn:aws:iam::{VENDOR}:user/carol": [{"Statement": [
{"Sid": "VendorReads", "Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]}],
f"arn:aws:iam::{VENDOR}:user/dave": [],
}
bucket_policy = {"Statement": [
{"Sid": "DenyInsecure", "Effect": "Deny", "Principal": "*", "Action": "s3:*", "Resource": [BUCKET, BUCKET + "/*"],
"Condition": {"Bool": {"aws:SecureTransport": "false"}}},
{"Sid": "AppWrites", "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCT}:role/app-role"},
"Action": "s3:PutObject", "Resource": BUCKET + "/incoming/*"},
{"Sid": "VendorReports", "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{VENDOR}:root"},
"Action": "s3:GetObject", "Resource": BUCKET + "/reports/*"},
]}
def ask(who, action, resource, **ctx):
ctx.setdefault("aws:SecureTransport", "true")
req = {"caller": who, "action": action, "resource": resource, "resource_account": ACCT, "ctx": ctx}
rp = bucket_policy if resource.startswith(BUCKET) else None
print(f"{who.split(':')[4][-4:]}/{who.split('/')[-1]:9} {action:22} {resource.split(':::')[-1].split(':')[-1]:32} "
f"{evaluate(req, identity[who], rp)}")
alice, bob, app = (f"arn:aws:iam::{ACCT}:{p}" for p in ("user/alice", "user/bob", "role/app-role"))
carol, dave = (f"arn:aws:iam::{VENDOR}:user/{u}" for u in ("carol", "dave"))
ask(alice, "s3:GetObject", BUCKET + "/incoming/a.png")
ask(alice, "s3:GetObject", BUCKET + "/incoming/a.png", **{"aws:SecureTransport": "false"})
ask(alice, "s3:DeleteObject", BUCKET + "/incoming/a.png")
ask(alice, "s3:DeleteObject", BUCKET + "/incoming/a.png", **{"aws:MultiFactorAuthPresent": "true"})
ask(app, "s3:PutObject", BUCKET + "/incoming/b.png")
ask(app, "s3:PutObject", BUCKET + "/reports/q1.csv")
ask(carol, "s3:GetObject", BUCKET + "/reports/q1.csv")
ask(dave, "s3:GetObject", BUCKET + "/reports/q1.csv")
ask(carol, "s3:GetObject", BUCKET + "/incoming/a.png")
ask(bob, "ec2:TerminateInstances", f"arn:aws:ec2:eu-west-1:{ACCT}:instance/i-0abc")
ask(bob, "iam:CreateAccessKey", f"arn:aws:iam::{ACCT}:user/bob")9012/alice s3:GetObject lab-app-uploads/incoming/a.png ALLOW (identity: ReadUploads, resource: None)
9012/alice s3:GetObject lab-app-uploads/incoming/a.png DENY explicit (resource: DenyInsecure)
9012/alice s3:DeleteObject lab-app-uploads/incoming/a.png DENY implicit
9012/alice s3:DeleteObject lab-app-uploads/incoming/a.png ALLOW (identity: DeleteWithMfa, resource: None)
9012/app-role s3:PutObject lab-app-uploads/incoming/b.png ALLOW (identity: None, resource: AppWrites)
9012/app-role s3:PutObject lab-app-uploads/reports/q1.csv DENY implicit
7777/carol s3:GetObject lab-app-uploads/reports/q1.csv ALLOW cross-account (identity: VendorReads, resource: VendorReports)
7777/dave s3:GetObject lab-app-uploads/reports/q1.csv DENY implicit (cross-account needs both sides)
7777/carol s3:GetObject lab-app-uploads/incoming/a.png DENY implicit (cross-account needs both sides)
9012/bob ec2:TerminateInstances instance/i-0abc ALLOW (identity: AllButIam, resource: None)
9012/bob iam:CreateAccessKey user/bob DENY implicit
Read the decisions line by line; each one exercises one rule:
- Alice's plain-HTTP read is stopped by the bucket's explicit deny, even though her identity policy allows it.
- Her delete without MFA finds no applicable allow (the condition key is missing, so
Boolis false); with MFA it is allowed. app-rolehas no identity policy at all and still writes toincoming/: in the same account the bucket policy alone is enough because it names the role directly. Outsideincoming/it gets nothing.- Carol in the vendor account can read
reports/because both sides allow; Dave, in the same vendor account but without an identity policy, can't; and Carol can't readincoming/because the bucket side doesn't allow it. - Bob's
NotAction: iam:*withResource: *reads like a restriction but is almost administrator: it allows terminating instances, deleting buckets and every other non-IAM action. Onlyiam:CreateAccessKeyfalls outside it.
How evaluation problems are detected
- In CloudTrail: denied calls carry
errorCodeAccessDenied(orClient.UnauthorizedOperationfor EC2), and recent AWS error messages name the kind of policy that denied ("explicit deny in a resource-based policy", "no identity-based policy allows"). A burst ofAccessDeniedfrom one principal across many services is the classic sign of someone exploring what a stolen key can do (Cloud Detections). - Offline: run an evaluator like this one, or the provider's policy simulator, over every principal × sensitive action × sensitive resource, and compare with what each principal is supposed to do.
- Static review of the patterns that are rarely intended:
NotActionorNotResourcewithAllow,Principal: "*"without conditions, account-root principals of accounts you don't recognise.
How it is fixed
- Replace
Allow+NotActionwith an explicit action list; keepNotActionforDenystatements, where it is a useful "deny everything except" guard. - Put unconditional denies where they protect everything (TLS-only, deny outside the organisation) on the resource side, so no identity policy can bypass them.
- For cross-account sharing, name the exact role in the resource policy and add an organisation or account condition rather than trusting a whole foreign account.
Pitfalls
- Expecting a resource-policy allow that names your own account root to grant access: it delegates, it doesn't grant.
- Forgetting that negated condition operators are true when the key is absent: a
StringNotEqualson a tag that the request doesn't carry lets the statement apply. - Writing
"Resource": "arn:aws:s3:::bucket"for object actions: objects arebucket/*, so the statement silently never matches.
Practice
1. Add {"Sid": "DenyDeleteOutsideOffice", "Effect": "Deny", "Action": "s3:DeleteObject", "Resource": "*", "Condition": {"NotIpAddress": {"aws:SourceIp": "192.0.2.0/24"}}} to Alice's policy. What happens to her MFA delete if the request carries no source IP?
NotIpAddress with a missing key is true, so the deny applies and the delete is denied. (Real requests that arrive through a VPC endpoint carry no aws:SourceIp, and calls an AWS service makes on your behalf carry the service's address instead of yours, which is why such guards usually add a Bool aws:ViaAWSService exception and use aws:VpcSourceIp or aws:SourceVpce for VPC traffic.)
2. Change the vendor statement's principal to arn:aws:iam::999988887777:user/carol. Can Dave read now? Does Carol still need her identity policy?
Dave still can't. Carol still needs her identity policy: cross-account access needs both sides no matter how precisely the resource policy names her.
3. Rewrite Bob's policy so it means what its author probably intended: "operations on EC2 and CloudWatch only".
{"Effect": "Allow", "Action": ["ec2:*", "cloudwatch:*", "logs:*"], "Resource": "*"}, then narrow further by resource or tag conditions where possible.
Test yourself
An identity policy allows s3:GetObject and the bucket policy denies it for requests without TLS. A plain-HTTP request arrives. Result?
- Allowed: identity policies win
- Denied: an explicit deny wins over any allow
- Allowed for the bucket owner
- Depends on statement order
Why could app-role write to incoming/ without any identity policy?
- Roles have implicit S3 access
- Same account: a resource policy that names the role directly is enough on its own
- PutObject needs no permission
- The bucket is public
Why was Dave denied while Carol (same vendor account) was allowed?
- Dave used HTTP
- Cross-account access needs an allow in the caller's identity policy too, and Dave has none
- The bucket names Carol only
- Dave lacks MFA
What does Allow + NotAction iam:* + Resource * effectively grant?
- Nothing
- Only IAM actions
- Every action in every service except IAM: close to administrator
- Read-only access