Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 05 · 50 minutes

Decide from the settings which storage buckets are public

After this lesson you can
  • Name the two ways a bucket becomes public and the four settings that block them
  • Decide with a program which buckets of an account are public, and why
  • Make a public bucket private with the smallest change and refuse plain HTTP
Lab files of this lesson (10)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A customer of Larkfield writes: "I searched for my order number and found a database dump of your shop on the open internet." Your lead forwards the mail with one line: "Find out which of our buckets the world can read, which of them are meant to be public, and how each one got that way." Storage that everyone can read is the cloud mistake that reaches the newspapers most often, and it can be decided from the settings alone.

Recall

Lesson 2: a bucket policy allows a user of the same account to read. The user has no identity-based policy. Is the request allowed?

Yes. Inside one account, an allow in the resource-based policy is enough.

Lesson 4: what is the difference between an access key ID and a secret access key?

The ID is a name that appears in logs. The secret signs the requests, is shown once, and must never be copied into code, logs or reports.

The idea

Amazon S3 stores objects (files) in buckets. Access to a bucket can come from three places.

WayWhat it isPublic when
Identity-based policyA policy on a user or role (lesson 2)Never: it names identities of your account
Bucket policyA resource-based policy on the bucketA statement allows "Principal": "*" with no condition that limits it to fixed values
ACL (access control list)An older list of grants on a bucket or an objectIt grants a permission to the group AllUsers (everyone) or AuthenticatedUsers (anyone with any AWS account)

For a policy, S3 starts from "public" and looks for a limit. A statement for everyone is not public when a condition ties it to a fixed value: a fixed address range in aws:SourceIp, a fixed network in aws:SourceVpc, a fixed account or organisation. A wildcard in that value, or a very wide address range, limits nothing.

Because mistakes were so common, AWS added Block Public Access: four switches that sit above policies and ACLs.

SettingWhat it does when it is on
BlockPublicAclsRefuses new public ACLs. It does not change the ACLs that exist.
IgnorePublicAclsIgnores every public ACL, old and new.
BlockPublicPolicyRefuses a new bucket policy that is public. It does not change the policy that exists.
RestrictPublicBucketsIf the bucket policy is public, only AWS services and principals of the owner's account get in.

The switches exist for the account and for each bucket, and the stricter one wins. So two settings stop a new mistake, and two settings stop an old one.

Is this bucket public today?
Public grant existsSwitch on?BlockedPUBLICa public ACL or a public policyyes, the matching switch holdsno, the worldcan read itPublic grant existsSwitch on?BlockedPUBLIC123
  1. Public grant exists → Switch on?: a public ACL or a public policy
  2. Switch on? → Blocked: yes, the matching switch holds
  3. Switch on? → PUBLIC: no, the world can read it

New buckets start safe: since April 2023 AWS switches all four settings on for a new bucket and disables ACLs. Old buckets, and buckets that a script made with other values, keep what they had. That is why you check.

Three more ideas belong to storage.

  • Encryption at rest: S3 encrypts every new object with a key that S3 manages (SSE-S3, written AES256 in the settings). With aws:kms, S3 uses a key from the key service: the AWS managed key for S3, or a key of your own, and with your own key you decide who may use it (lesson 9).
  • Encryption in transit: S3 answers over HTTPS and over plain HTTP. A Deny statement with the condition aws:SecureTransport equal to false refuses every request that does not use TLS ("Networking hands-on", lesson 9).
  • A pre-signed URL is a link that carries a signature and an end time. Anyone who has the link can do the one thing that it names, with the rights of the signer, until it ends. It shares one object with no public bucket. It is also a credential: treat the link like a password.
A pre-signed URL (shortened)
https://larkfield-orders.s3the bucket/reports/q3.pdfthe one object?X-Amz-Credential=AKIAkey id of the signer&X-Amz-Expires=900seconds until it ends&X-Amz-Signature=5d1cproof that nothing changedhttps://larkfield-orders.s3the bucket/reports/q3.pdfthe one object?X-Amz-Credential=AKIAkey id of the signer&X-Amz-Expires=900seconds until it ends&X-Amz-Signature=5d1cproof that nothing changed
Same idea, other namesAWSMicrosoft AzureGoogle Cloud
Container for objectsS3 bucketBlob container in a storage accountCloud Storage bucket
"Everyone""Principal": "*", the group AllUsersAnonymous access level of a containerThe principals allUsers and allAuthenticatedUsers
The switch above itBlock Public AccessThe account setting AllowBlobPublicAccessPublic access prevention
A signed link with an end timePre-signed URLShared access signature (SAS)Signed URL

Worked example

1. Read the settings of one bucket

account/buckets.json is a file in our own shape. It joins what four different API calls return: the Block Public Access settings of the account and of each bucket, the bucket policy, the ACL and the encryption setting. The policies and the names of the settings are the real ones.

next(x for x in items if test) returns the first item that passes the test. Here it finds the bucket with one name.

python3 -c "
import json
data = json.load(open('account/buckets.json'))
print('account:', data['account_public_access_block'])
b = next(b for b in data['buckets'] if b['name'] == 'larkfield-uploads')
print(json.dumps({k: b[k] for k in ('name', 'public_access_block', 'policy', 'acl')}, indent=1))" | head -n 24
account: {'BlockPublicAcls': True, 'IgnorePublicAcls': False, 'BlockPublicPolicy': False, 'RestrictPublicBuckets': False}
{
 "name": "larkfield-uploads",
 "public_access_block": {
  "BlockPublicAcls": false,
  "IgnorePublicAcls": false,
  "BlockPublicPolicy": false,
  "RestrictPublicBuckets": false
 },
 "policy": null,
 "acl": [
  {
   "Grantee": {
    "Type": "Group",
    "URI": "http://acs.amazonaws.com/groups/global/AllUsers"
   },
   "Permission": "READ"
  }
 ]
}

The account has one of the four switches on. This bucket has none, no policy, and an ACL that grants READ to the group AllUsers.

2. Save the checker

buckets.py decides each bucket in three steps. The first step finds the statements of the policy that are for everyone and have no fixed limit.

def public_statements(policy):
    """The Allow statements that give access to everyone with no fixed limit."""
    out = []
    for st in as_list((policy or {}).get("Statement", [])):
        if st["Effect"] != "Allow" or not for_everyone(st["Principal"]):
            continue
        pairs = [(k, v) for op, values in st.get("Condition", {}).items() if "Not" not in op for k, v in values.items()]
        if not any(k in LIMITING and all(fixed(k, v) for v in as_list(v)) for k, v in pairs):
            out.append(st)
    return out

for_everyone is true for "*" and for {"AWS": "*"}. The long line collects the keys and values of the condition (not those of a negated operator such as NotIpAddress, which limits nothing) and asks: is one of them a limiting key (aws:SourceIp, aws:SourceVpc and a few more) with a fixed value? The function fixed rejects a value with a wildcard and an address range wider than /8 (for IPv6, /32).

The second step, public_grants, finds the grants to the two public groups. The third, judge, joins the switches of the account and the bucket (the stricter wins) and gives one of three results: PUBLIC, blocked (it would be public, but a switch stops it) or private. tls_only looks for the Deny on plain HTTP. This is a simple model of the rules: it knows the positive operators only, and it does not read object ACLs or access points. Open the block and save the file.

The finished file: buckets.py

buckets.py

"""buckets.py: decide which buckets of an account are public, and why.

    python3 buckets.py [FILE]        default file: account/buckets.json. Exit code 1 when a bucket is public by mistake.
"""
import ipaddress
import json
import sys

from policy_eval import as_list

PUBLIC_GROUPS = ("AllUsers", "AuthenticatedUsers")
# Condition keys that can make a statement for "everyone" non-public, when their value is fixed.
LIMITING = {"aws:SourceIp", "aws:SourceVpc", "aws:SourceVpce", "aws:SourceArn", "aws:SourceAccount", "aws:SourceOwner",
            "aws:PrincipalOrgID", "aws:userid"}


def fixed(key, value):
    """A fixed value has no wildcard. An address range must be narrow: /8 or smaller for IPv4, /32 for IPv6."""
    if key == "aws:SourceIp":
        net = ipaddress.ip_network(value, strict=False)  # strict=False accepts a range with host bits set
        return net.prefixlen >= (8 if net.version == 4 else 32)
    return "*" not in value and "?" not in value


def for_everyone(principal):
    return principal == "*" or (isinstance(principal, dict) and "*" in as_list(principal.get("AWS", [])))


def public_statements(policy):
    """The Allow statements that give access to everyone with no fixed limit."""
    out = []
    for st in as_list((policy or {}).get("Statement", [])):
        if st["Effect"] != "Allow" or not for_everyone(st["Principal"]):
            continue
        pairs = [(k, v) for op, values in st.get("Condition", {}).items() if "Not" not in op for k, v in values.items()]
        if not any(k in LIMITING and all(fixed(k, v) for v in as_list(v)) for k, v in pairs):
            out.append(st)
    return out


def public_grants(acl):
    return [g for g in acl if g["Grantee"].get("URI", "").rsplit("/", 1)[-1] in PUBLIC_GROUPS]


def tls_only(policy):
    """True when a Deny statement refuses every request that does not use TLS."""
    return any(st["Effect"] == "Deny" and st.get("Condition", {}).get("Bool", {}).get("aws:SecureTransport") == "false"
               for st in as_list((policy or {}).get("Statement", [])))


def judge(bucket, account_block):
    """Return (status, reasons). The stricter of the account setting and the bucket setting wins."""
    block = {k: account_block[k] or bucket["public_access_block"][k] for k in account_block}
    open_now, stopped = [], []
    if public_grants(bucket["acl"]):
        perms = "+".join(g["Permission"] for g in public_grants(bucket["acl"]))
        (stopped if block["IgnorePublicAcls"] else open_now).append(
            f"ACL gives {perms} to a public group" + (", ignored by IgnorePublicAcls" if block["IgnorePublicAcls"] else ""))
    if public_statements(bucket["policy"]):
        actions = ",".join(a for st in public_statements(bucket["policy"]) for a in as_list(st["Action"]))
        (stopped if block["RestrictPublicBuckets"] else open_now).append(
            f"policy allows {actions} to everyone" + (", stopped by RestrictPublicBuckets" if block["RestrictPublicBuckets"] else ""))
    return ("PUBLIC" if open_now else "blocked" if stopped else "private"), open_now + stopped


def findings(data):
    out = []
    if not all(data["account_public_access_block"].values()):
        off = [k for k, v in data["account_public_access_block"].items() if not v]
        out.append({"severity": "medium", "code": "ACCOUNT-BLOCK", "subject": "account", "text": "not set for the account: " + ", ".join(off)})
    for b in data["buckets"]:
        status, why = judge(b, data["account_public_access_block"])
        if status == "PUBLIC":
            intended = b["intended_public"]
            out.append({"severity": "low" if intended else "critical", "code": "PUBLIC-OK" if intended else "PUBLIC",
                        "subject": f"bucket {b['name']}", "text": "; ".join(why)})
        elif status == "blocked":
            out.append({"severity": "medium", "code": "ONE-SETTING", "subject": f"bucket {b['name']}", "text": "; ".join(why)})
        if not tls_only(b["policy"]):
            out.append({"severity": "low", "code": "NO-TLS-RULE", "subject": f"bucket {b['name']}", "text": "no statement refuses plain HTTP"})
    return out


if __name__ == "__main__":
    with open(sys.argv[1] if len(sys.argv) > 1 else "account/buckets.json") as src:
        data = json.load(src)
    public = mistakes = 0
    for b in data["buckets"]:
        status, why = judge(b, data["account_public_access_block"])
        public += status == "PUBLIC"
        mistakes += status == "PUBLIC" and not b["intended_public"]
        tls = "tls-only" if tls_only(b["policy"]) else "http-ok "
        print(f"{b['name']:22s} {status:8s} {tls} {b['encryption']['SSEAlgorithm']:8s} {'; '.join(why)}")
    print(f"{public} public, {mistakes} of them by mistake")
    sys.exit(1 if mistakes else 0)

3. Check every bucket

python3 buckets.py
echo "exit code $?"
larkfield-orders       private  http-ok  aws:kms  
larkfield-site         PUBLIC   http-ok  AES256   policy allows s3:GetObject to everyone
larkfield-backups      PUBLIC   http-ok  AES256   policy allows s3:GetObject,s3:ListBucket to everyone
larkfield-reports      blocked  http-ok  AES256   policy allows s3:GetObject to everyone, stopped by RestrictPublicBuckets
larkfield-uploads      PUBLIC   http-ok  AES256   ACL gives READ to a public group
larkfield-logs         private  tls-only AES256   
larkfield-partner      private  http-ok  AES256   
larkfield-dev-scratch  blocked  http-ok  AES256   ACL gives WRITE to a public group, ignored by IgnorePublicAcls
larkfield-media        PUBLIC   http-ok  AES256   policy allows s3:GetObject to everyone
4 public, 3 of them by mistake
exit code 1

Four buckets are public. One of them is the web site, which must be (the field intended_public of our snapshot records that decision). The other three are mistakes.

4. Explain each result

  • larkfield-backups: the policy lets everyone list the bucket and read every object. This is the dump that the customer found.
  • larkfield-uploads: public through its ACL. The account has BlockPublicAcls on, and it does not help: that switch refuses new public ACLs and leaves old ones in place. IgnorePublicAcls is the one that would stop it.
  • larkfield-media: the statement for everyone has a condition, but the range is 0.0.0.0/0, every address. A condition that limits nothing is no limit.
  • larkfield-partner: the same kind of statement with the fixed range 198.51.100.0/24. Not public.
  • larkfield-reports and larkfield-dev-scratch: blocked. A public policy and a public ACL exist, and one switch each keeps the world out. They are one setting away from a leak, so they belong on the list.
  • Only larkfield-logs refuses plain HTTP.

5. See what a wide switch would do

The quick fix is to switch all four settings on for the account. Try it in a copy of the file before anyone does it in production. dict.fromkeys(d, True) makes a new dictionary with the keys of d and the value True for each.

python3 -c "
import json
data = json.load(open('account/buckets.json'))
data['account_public_access_block'] = dict.fromkeys(data['account_public_access_block'], True)
json.dump(data, open('buckets-all-on.json', 'w'), indent=1)"
python3 buckets.py buckets-all-on.json | grep -E "site|public,"
larkfield-site         blocked  http-ok  AES256   policy allows s3:GetObject to everyone, stopped by RestrictPublicBuckets
0 public, 0 of them by mistake

Nothing is public, and the web site is gone too. The account switch is the right end state for an account that serves nothing to the public, and a public site then belongs in an account of its own or behind a content delivery service. Until then, fix the buckets one by one.

Your turn

Copy account/buckets.json to buckets-fixed.json and repair it. Change the file by hand or with a few lines of Python.

  • Make the three buckets that are public by mistake private. Use the smallest change that fits each cause, and keep the web site public.
  • Add a statement to the policy of larkfield-orders that refuses every request without TLS, on the bucket and on its objects. Use the statement of larkfield-logs as a model.

Then run the checker on your file.

Check yourself

An account has BlockPublicAcls and BlockPublicPolicy on, and the other two settings off. Can a bucket of that account be public?

Yes. Those two settings refuse new public ACLs and new public policies. A bucket that was public before they were switched on stays public. IgnorePublicAcls and RestrictPublicBuckets are the settings that act on what already exists.

A bucket policy allows s3:GetObject to "Principal": "*" with the condition aws:SourceIp equal to 198.51.100.0/24. Is the bucket public?

No. The statement is for everyone, but the condition ties it to a fixed, narrow address range, so S3 does not count the policy as public. Whether that range is the right one is a different question, and the review must still ask it.

Every object of a public bucket is encrypted at rest with SSE-S3. Does the encryption protect the data from a stranger who downloads it?

No. S3 decrypts the object for every request that is allowed, and a public bucket allows the stranger. Encryption at rest with a key that S3 manages protects against someone who gets at the disks. With a key of your own in the key service, the reader would also need the right to use that key, which a stranger does not have (lesson 9).

Field notes

  • On a real account, get-bucket-acl shows the ACL that S3 enforces. With IgnorePublicAcls on, get-bucket-acl shows no public grant. A bucket in the state blocked because of an ACL therefore does not look public in that call, so read the Block Public Access setting as well. IAM Access Analyzer for S3 lists the buckets that are public or shared with other accounts, with the statement that causes it. Use it as the second opinion on a checker like this one.
  • A public bucket policy with s3:ListBucket is worse than one with s3:GetObject alone: listing gives the stranger the names of all objects. With GetObject only, they must know or guess a name.
  • Object ACLs are a second layer below the bucket: one object can be public in a private bucket. Disable ACLs for the bucket ("bucket owner enforced") and that layer is gone. New buckets have it by default.
  • Keep a pre-signed URL short-lived. The command line and the libraries accept up to seven days, and a link also ends when the credentials that signed it end. Take the current limits from the S3 documentation.
  • Switch on versioning for buckets that hold records, so that a delete or an overwrite can be undone, and log who reads them (data events, lesson 7).