A backup script that could delete everything
A backup script copies one folder into one bucket each night. To save time, its role was allowed every S3 action on every resource.
Then the script's key leaked. Whoever held it could read, change or delete every bucket in the account.
The one rule
Warning
Everything in this module happens in the practice cloud of your own lab. Testing a cloud account you do not own needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can narrow a cloud role's policy to the least privilege its job needs.
Key words
| Word | What it means | Example |
|---|---|---|
| Role | an identity a program takes on, with no password | |
| Policy | a JSON document of what is allowed or denied | |
| Action | one API call a policy names | s3:GetObject |
| Resource | the thing an action is on, named by its ARN | |
| Least privilege | only the access a job needs | |
| Wildcard | a * that matches anything |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsDeny wins, then allow, then nothing
A policy holds statements. Each says an Effect (Allow or Deny), the Actions and the Resources, and sometimes a Condition.
AWS checks a request in a fixed order. A Deny that matches refuses it. Otherwise an Allow that matches lets it through. Otherwise it is refused, which is called an implicit deny.
Three requests, one decision each
| Request | Statements that match | Decision |
|---|---|---|
| Put a backup in backups/ | Allow on backups/* | Allowed |
| Read an invoice | None | Implicit deny |
| Delete a backup | Allow and an explicit Deny | Explicit deny |
The cells students fill in are left blank in this preview.
Try it: what s3:* allows
statement = {"Effect": "Allow", "Action": "s3:*", "Resource": "*"}
actions = ["s3:GetObject", "s3:DeleteBucket", "s3:PutBucketPolicy"]
for action in actions:
prefix = statement["Action"].rstrip("*")
ok = statement["Action"] == "*" or action.startswith(prefix)
print(action, "allowed" if ok else "refused")
# Change the Action to "s3:Get*". Which actions are still allowed?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsYour stack does not check IAM
Ask your stack for IAM and it refuses, because IAM is not switched on in this lab. Even with IAM on, MiniStack stores policies and enforces none, and its simulator answers "allowed" to everything.
So you check the role's policy yourself. You write it as a file and run your own analyzer, as IAM Access Analyzer's policy checks do on AWS.
Point the aws command at your stack
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 AWS_ENDPOINT_URL=http://cloud:4566Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask your stack for IAM roles
aws iam list-rolesShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the backup role's first policy
mkdir -p ~/cs && printf '%s\n' '{"Version":"2012-10-17","Statement":[{"Sid":"Backups","Effect":"Allow","Action":"s3:*","Resource":"*"},{"Sid":"Launch","Effect":"Allow","Action":"iam:PassRole","Resource":"*"}]}' > ~/cs/wide.jsonShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the analyzer, part 1
mkdir -p ~/cs && printf '%s\n' 'import json' 'import sys' '' 'RISKY = ["iam:PassRole", "iam:CreateAccessKey", "iam:AttachRolePolicy", "iam:PutRolePolicy"]' '' '' 'def as_list(value):' ' if isinstance(value, list):' ' return value' ' return [value]' '' '' 'def check(policy):' ' found = []' ' for number, statement in enumerate(as_list(policy["Statement"]), start=1):' ' if not statement.get("Effect") == "Allow":' ' continue' ' actions = as_list(statement.get("Action", []))' ' resources = as_list(statement.get("Resource", []))' ' if "NotAction" in statement:' ' found.append((number, "allows everything except a list (NotAction)"))' ' for action in actions:' ' if action == "*":' ' found.append((number, "every action in every service"))' ' elif action.endswith(":*"):' ' found.append((number, "every action in " + action.split(":")[0]))' > ~/cs/analyse.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the analyzer, part 2
printf '%s\n' ' elif action in RISKY:' ' found.append((number, action + " can hand a stronger role to a service"))' ' if "*" in resources:' ' found.append((number, "every resource in the account"))' ' return found' '' '' 'policy = json.load(open(sys.argv[1]))' 'findings = check(policy)' 'for number, words in findings:' ' print("statement", number, ":", words)' 'print(len(findings), "findings in", sys.argv[1])' >> ~/cs/analyse.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Analyse the first policy
cd ~/cs && python3 analyse.py wide.jsonShown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think a wildcard is harmless because the script only ever calls two actions. A policy is what a stolen key can do, not what the script does. Grant only the actions and resources the job needs.
Check
Have a go
Check
3 questionsName the actions and the folder
The script reads and writes backups, and lists the bucket. So the narrow policy allows s3:GetObject and s3:PutObject on shop-media/backups/* and s3:ListBucket on the bucket.
It also denies s3:DeleteObject everywhere, so even a later Allow cannot let the script delete. PassRole goes, because the job never needs it.
Write the narrow policy
mkdir -p ~/cs && printf '%s\n' '{"Version":"2012-10-17","Statement":[{"Sid":"ReadWriteBackups","Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":"arn:aws:s3:::shop-media/backups/*"},{"Sid":"ListBucket","Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::shop-media"},{"Sid":"NeverDelete","Effect":"Deny","Action":"s3:DeleteObject","Resource":"*"}]}' > ~/cs/narrow.jsonShown here, not run. Press Start lab to type it into your own lab’s terminal.
Analyse the narrow policy
cd ~/cs && python3 analyse.py narrow.jsonShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the decision checker, part 1
mkdir -p ~/cs && printf '%s\n' 'import fnmatch' 'import json' 'import sys' '' '' 'def as_list(value):' ' if isinstance(value, list):' ' return value' ' return [value]' '' '' 'def matches(statement, action, resource):' ' actions = [a.lower() for a in as_list(statement.get("Action", []))]' ' resources = as_list(statement.get("Resource", []))' ' action_ok = any(fnmatch.fnmatchcase(action.lower(), a) for a in actions)' ' resource_ok = any(fnmatch.fnmatchcase(resource, r) for r in resources)' ' return action_ok and resource_ok' '' '' 'def decide(policy, action, resource):' ' statements = as_list(policy["Statement"])' ' for statement in statements:' ' if statement["Effect"] == "Deny" and matches(statement, action, resource):' ' return "DENY: an explicit Deny matches"' ' for statement in statements:' ' if statement["Effect"] == "Allow" and matches(statement, action, resource):' > ~/cs/can.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the decision checker, part 2
printf '%s\n' ' return "ALLOW: " + statement.get("Sid", "a statement") + " matches"' ' return "DENY: no statement allows it"' '' '' 'policy = json.load(open(sys.argv[1]))' 'print(sys.argv[2], "on", sys.argv[3])' 'print(decide(policy, sys.argv[2], sys.argv[3]))' >> ~/cs/can.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask about three requests
cd ~/cs && python3 can.py narrow.json s3:PutObject arn:aws:s3:::shop-media/backups/mon.tar && python3 can.py narrow.json s3:GetObject arn:aws:s3:::shop-media/invoices/1042.txt && python3 can.py narrow.json s3:DeleteObject arn:aws:s3:::shop-media/backups/mon.tarShown here, not run. Press Start lab to type it into your own lab’s terminal.
Catch wide policies before and after
Before: run the analyzer on every change to a policy and fail the change on any finding. After: watch which actions a role really uses and remove the rest.
On AWS, IAM Access Analyzer checks policies and reports unused access, and CloudTrail records every call, which lesson 5 reads.
Assignment: decide like IAM does
Write the three pieces of a small policy checker.
matches(pattern, value) is True when value fits a pattern where * stands for any characters. decide(statements, action, resource) answers "explicit deny", "allow" or "implicit deny", in that order of checking. Actions match without caring about capitals. wildcards(statements) gives the Sid of every Allow statement with "*" as an action or a resource.
def matches(pattern, value):
# True when value fits pattern. A * stands for any characters.
return False
def decide(statements, action, resource):
# "explicit deny", "allow" or "implicit deny".
# Actions match without caring about capitals, resources exactly.
return "allow"
def wildcards(statements):
# The Sid of every Allow statement with "*" as an action or a resource.
return []
Make a free account to save your work and track your progress.
Exit quiz
Have a go