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

Free lesson

Public buckets and bucket policies

After this lesson: I can lock down a bucket with block public access and a policy that requires TLS.

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

One star in a policy

A shop wanted its product photos on its website, so somebody added a bucket policy that let anyone read. They added it to the wrong bucket, the one with the invoices.

The whole mistake was one star in one line of JSON.

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 lock down a bucket with block public access and a policy that requires TLS.

Key words

WordWhat it meansExample
Bucket policya policy that sits on a bucket and names who
Principalwho a statement is about"*"
Block public accessfour switches that stop a bucket going public
Conditiona test a request must pass for a statement to apply
TLSencryption for data on its way over a network

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

Principal "*" means anyone at all

A role's policy says what that role may do. A bucket policy sits on the bucket instead and says who may do what to it.

An Allow statement with a Principal of "*" and no Condition means anyone on the internet, signed in or not. A Deny with "*" is different: it refuses everyone that matches.

Try it: anyone or a named role?

Code: python
statements = [
    {"Sid": "PublicRead", "Effect": "Allow", "Principal": "*"},
    {"Sid": "Staff", "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::111122223333:role/staff"}},
]
for statement in statements:
    anyone = statement["Principal"] == "*"
    print(statement["Sid"], "anyone" if anyone else "named role")
# Add a Deny statement with Principal "*". Is that one a problem?

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

Make the mistake in your own stack

Make a bucket for invoices, put one invoice in it and give it the public policy from the hook. Then write bucketcheck.py, which reads the bucket's settings back with the aws command and judges them.

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.

Make the invoices bucket and add an invoice

Command
aws s3 mb s3://shop-invoices && printf 'invoice 1042\n' | aws s3 cp - s3://shop-invoices/2026/1042.txt

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

Write the public policy

Command
mkdir -p ~/cs && printf '%s\n' '{"Version":"2012-10-17","Statement":[{"Sid":"PublicRead","Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::shop-invoices/*"}]}' > ~/cs/public.json

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

Put the public policy on the bucket

Command
cd ~/cs && aws s3api put-bucket-policy --bucket shop-invoices --policy file://public.json

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

Write the bucket check, part 1

Command
mkdir -p ~/cs && printf '%s\n' 'import json' 'import subprocess' 'import sys' '' '' 'def aws(*args):' '    done = subprocess.run(["aws", "s3api", *args, "--output", "json"], capture_output=True, text=True)' '    if not done.returncode == 0:' '        return None' '    return json.loads(done.stdout or "{}")' '' '' 'def as_list(value):' '    if isinstance(value, list):' '        return value' '    return [value]' '' '' 'def public(statement):' '    who = statement.get("Principal")' '    anyone = who == "*" or (isinstance(who, dict) and "*" in as_list(who.get("AWS", [])))' '    return statement.get("Effect") == "Allow" and anyone and "Condition" not in statement' '' '' 'def needs_tls(statement):' '    test = statement.get("Condition", {}).get("Bool", {}).get("aws:SecureTransport")' '    return statement.get("Effect") == "Deny" and str(test).lower() == "false"' '' '' 'bucket = sys.argv[1]' 'problems = []' 'block = aws("get-public-access-block", "--bucket", bucket)' > ~/cs/bucketcheck.py

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

Write the bucket check, part 2

Command
printf '%s\n' 'settings = (block or {}).get("PublicAccessBlockConfiguration", {})' 'for name in ["BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets"]:' '    if not settings.get(name):' '        problems.append("block public access: " + name + " is off")' 'answer = aws("get-bucket-policy", "--bucket", bucket)' 'statements = as_list(json.loads(answer["Policy"])["Statement"]) if answer else []' 'for statement in statements:' '    if public(statement):' '        problems.append("policy: " + statement.get("Sid", "a statement") + " allows anyone")' 'if not any(needs_tls(s) for s in statements):' '    problems.append("policy: no statement refuses plain HTTP")' 'for line in problems:' '    print("FAIL", line)' 'print(bucket, ":", len(problems), "problems")' >> ~/cs/bucketcheck.py

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

Check the bucket

Command
cd ~/cs && python3 bucketcheck.py shop-invoices

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

A common mistake

Warning

Many people think a bucket is private while nobody knows its name. Bucket names are guessed and scanned for all the time. The policy and block public access decide who can read, so check those, never the name.

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

Block public access, then refuse plain HTTP

Turn on all four block public access switches: two stop public ACLs, two stop public policies. Then replace the policy with one that refuses any request not made over TLS.

That statement is a Deny for everyone when aws:SecureTransport is "false". Run the check again.

Turn on block public access

Command
aws s3api put-public-access-block --bucket shop-invoices --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true

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

Write the policy that requires TLS

Command
mkdir -p ~/cs && printf '%s\n' '{"Version":"2012-10-17","Statement":[{"Sid":"OnlyTLS","Effect":"Deny","Principal":"*","Action":"s3:*","Resource":["arn:aws:s3:::shop-invoices","arn:aws:s3:::shop-invoices/*"],"Condition":{"Bool":{"aws:SecureTransport":"false"}}}]}' > ~/cs/tls.json

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

Put the TLS policy and check again

Command
cd ~/cs && aws s3api put-bucket-policy --bucket shop-invoices --policy file://tls.json && python3 bucketcheck.py shop-invoices

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

What AWS refuses and your stack accepts

On AWS, with BlockPublicPolicy on, putting a public policy is refused with AccessDenied. Your stack stores settings and enforces none, so it accepts it. Try it, then put the TLS policy back.

Try the public policy again, then undo it

Command
cd ~/cs && aws s3api put-bucket-policy --bucket shop-invoices --policy file://public.json && echo accepted && aws s3api put-bucket-policy --bucket shop-invoices --policy file://tls.json

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

Catch a public bucket the day it happens

Turn block public access on for the whole account, so one bucket cannot be opened by mistake. Check every bucket every day, as bucketcheck.py does.

On AWS, the AWS Config rules s3-bucket-public-read-prohibited and s3-bucket-ssl-requests-only do this. Alert on every PutBucketPolicy, which lesson 5 does.

Assignment: judge a bucket policy

Judge a bucket from its policy and its block public access settings.

is_public(statement) is True for an Allow whose Principal is "*" or {"AWS": "*"} with no Condition. requires_tls(policy) is True when a Deny statement has the Bool condition aws:SecureTransport set to "false". problems(policy, block) returns a sorted list of "block-off", "public-statement" and "no-tls".

Code: python
def is_public(statement):
    # An Allow for Principal "*" (or {"AWS": "*"}) with no Condition.
    return False


def requires_tls(policy):
    # True when a Deny statement has Bool aws:SecureTransport "false".
    return False


def problems(policy, block):
    # A sorted list of "block-off", "public-statement" and "no-tls".
    # block is the four block public access settings, name to True or False.
    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.