Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Least privilege for a cloud role

After this lesson: I can narrow a cloud role's policy to the least privilege its job needs.

65 min lesson11 commandsCloud lab: practise S3 buckets, SQS queues and DynamoDB tables with the AWS command line

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can narrow a cloud role's policy to the least privilege its job needs.

Key words

WordWhat it meansExample
Rolean identity a program takes on, with no password
Policya JSON document of what is allowed or denied
Actionone API call a policy namess3:GetObject
Resourcethe thing an action is on, named by its ARN
Least privilegeonly the access a job needs
Wildcarda * that matches anything

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Deny 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

RequestStatements that matchDecision
Put a backup in backups/Allow on backups/*Allowed
Read an invoiceNoneImplicit deny
Delete a backupAllow and an explicit DenyExplicit deny

The cells students fill in are left blank in this preview.

Try it: what s3:* allows

Code: python
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your 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

Command
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 AWS_ENDPOINT_URL=http://cloud:4566

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask your stack for IAM roles

Command
aws iam list-roles

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the backup role's first policy

Command
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.json

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the analyzer, part 1

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the analyzer, part 2

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Analyse the first policy

Command
cd ~/cs && python3 analyse.py wide.json

Shown 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Name 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

Command
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.json

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Analyse the narrow policy

Command
cd ~/cs && python3 analyse.py narrow.json

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the decision checker, part 1

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the decision checker, part 2

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask about three requests

Command
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.tar

Shown 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.