Cloud and deployment · Intermediate · 22 min
Lock down an S3 bucket: block public access, require TLS and encrypt by default
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4
You will have a private S3 bucket with public access blocked at account and bucket level, ACLs switched off, a bucket policy that refuses plain HTTP and the wrong encryption key, SSE-KMS default encryption with a bucket key, versioning, and a script that audits all of it.
On this page
Most S3 leaks are not clever attacks. Someone turned off a public access setting to make one file shareable, an old ACL granted read access to "all users", or an app wrote data over plain HTTP from a network nobody trusted. AWS has closed many of these gaps by default for new buckets, but defaults can be changed, older buckets predate them, and auditors will ask you to prove the settings are what you say.
In this tutorial you build one bucket the careful way and then write a script that checks it. You will:
- check Block Public Access for the whole account and for the bucket
- switch off ACLs, so only policies decide who gets in
- write a bucket policy that refuses any request without TLS and any upload that asks for the wrong encryption key
- make SSE-KMS with an S3 Bucket Key the default encryption, and see what that costs compared with SSE-S3
- turn on versioning, with a rule that removes old versions after 30 days
- list everyone who can reach the bucket, then run an audit script over it
This is a private bucket that your own apps and team read and write. If you want a bucket that only CloudFront reads for a public website, follow /tutorials/host-a-static-site-on-s3-and-cloudfront instead; the ideas here still apply to it.
Cost. The bucket and a few test objects cost almost nothing, but the KMS key you create is billed at 1 USD a month, prorated by the hour, plus requests beyond a free allowance of 20,000 a month (AWS KMS pricing page, checked 26 November 2026). The clean-up step schedules the key for deletion, and AWS does not charge for keys while they wait to be deleted.
Step 1 · Install the AWS CLI and set names
Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. If aws --version already shows 2.42 or later, skip to the variables below:
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --versionThe CLI gets no updates from apt. To upgrade later, run the same commands with a newer version and sudo ./aws/install --update. The archive is a large download; on prepaid mobile data, fetch it once on Wi-Fi and keep the zip.
If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder; /tutorials/set-up-the-aws-cli-with-sso-and-named-profiles shows how to make one). Then set the names used in every later command. Bucket names are global across all of AWS, so the account ID goes into the name to avoid a clash:
mkdir -p ~/locked-demo
cd ~/locked-demo
export AWS_REGION=eu-west-1
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export BUCKET=locked-demo-$ACCOUNT_ID
echo "$BUCKET in $AWS_REGION"eu-west-1 (Ireland) is only an example. If your users are in southern Africa and your account has the Cape Town Region enabled, af-south-1 keeps the data closer to them; it is an opt-in Region, so it must be switched on in the account first. Keep this terminal open: the variables disappear when it closes.
Create the bucket. Outside us-east-1, S3 needs the Region repeated as a location constraint:
aws s3api create-bucket --bucket "$BUCKET" \
--create-bucket-configuration LocationConstraint="$AWS_REGION"Check it worked
aws --version starts with aws-cli/2.42.4. The echo prints something like locked-demo-123456789012 in eu-west-1, and create-bucket returns a Location that contains your bucket name. aws s3api head-bucket --bucket "$BUCKET" prints a BucketRegion of eu-west-1.
Step 2 · Block public access for the account and the bucket
Block Public Access is four switches that sit above every policy and ACL:
BlockPublicAclsrefuses requests that try to set a public ACL.IgnorePublicAclsmakes S3 ignore any public ACL that already exists.BlockPublicPolicyrefuses a bucket policy that would make the bucket public.RestrictPublicBucketslimits a bucket that already has a public policy to AWS services and your own account.
They exist at the account level and the bucket level, and S3 applies whichever is stricter. Read the account setting first:
aws s3control get-public-access-block --account-id "$ACCOUNT_ID" \
|| echo "No account-level Block Public Access is set"If you see four true values, the account is already covered. If the command reports NoSuchPublicAccessBlockConfiguration, or any value is false, nothing at account level stops a bucket from being made public.
Before you turn it on for the account, check whether anything in the account is meant to be public, such as an old static website bucket served straight from S3. The account setting applies to every bucket you own, in every Region, and a public site would stop working. Once you are sure, turn on all four:
aws s3control put-public-access-block --account-id "$ACCOUNT_ID" \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=trueNew buckets block public access by default, but set the bucket level explicitly too. If someone later relaxes the account setting, this bucket stays closed:
aws s3api put-public-access-block --bucket "$BUCKET" \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api get-public-access-block --bucket "$BUCKET"Check it worked
Both aws s3control get-public-access-block --account-id "$ACCOUNT_ID" and get-public-access-block --bucket show all four settings as true.
Step 3 · Switch off ACLs
ACLs are S3's oldest permission system: a list of grants on each bucket and each object. They are hard to audit because every object can carry its own. The Object Ownership setting Bucket owner enforced switches them off. Your account then owns every object, whoever uploaded it, and only policies decide access. It is the default for new buckets; setting it makes it explicit, and on an older bucket it is the change that matters:
aws s3api put-bucket-ownership-controls --bucket "$BUCKET" \
--ownership-controls 'Rules=[{ObjectOwnership=BucketOwnerEnforced}]'
aws s3api get-bucket-ownership-controls --bucket "$BUCKET"On an existing bucket, read its ACLs and bucket policy before you do this: any access granted only by an ACL stops working, so move it into the bucket policy first.
With ACLs off, an upload that tries to set one is refused. Try it with a test file:
echo "hello from a locked bucket" > hello.txtaws s3api put-object --bucket "$BUCKET" --key acl-test.txt --body hello.txt --acl public-readCheck it worked
get-bucket-ownership-controls shows "ObjectOwnership": "BucketOwnerEnforced". The put-object with --acl public-read fails with AccessControlListNotSupported, and no acl-test.txt appears in aws s3 ls "s3://$BUCKET".
Step 4 · Choose and set default encryption
Every new object in S3 has been encrypted since January 2023. The question is which key protects it:
- SSE-S3 uses keys that S3 owns and manages. There is no extra charge and nothing to configure. Anyone who can read the object through S3 gets the plaintext.
- SSE-KMS uses a key in AWS KMS that you control. A reader needs permission on the object and
kms:Decrypton the key, so the key policy is a second lock, and every use of the key is logged in CloudTrail. You pay for the key and for KMS requests.
Without help, SSE-KMS calls KMS for every object written or read, and a busy bucket turns that into a large request bill. An S3 Bucket Key lets S3 reuse a short-lived bucket-level key, which AWS says cuts KMS request costs by up to 99 percent. Use SSE-S3 when the bucket holds nothing sensitive; use SSE-KMS with a bucket key when you need to control and log who can decrypt. This tutorial uses SSE-KMS.
Create a customer managed key with a friendly alias, and keep its ARN in a variable:
export KEY_ARN=$(aws kms create-key --description "Default key for $BUCKET" \
--tags TagKey=project,TagValue=locked-demo \
--query KeyMetadata.Arn --output text)
aws kms create-alias --alias-name alias/locked-demo --target-key-id "$KEY_ARN"
echo "$KEY_ARN"Make it the bucket's default, with the bucket key on:
cat > encryption.json <<JSON
{
"Rules": [
{
"ApplyServerSideEncryptionByDefault": {
"SSEAlgorithm": "aws:kms",
"KMSMasterKeyID": "$KEY_ARN"
},
"BucketKeyEnabled": true
}
]
}
JSON
aws s3api put-bucket-encryption --bucket "$BUCKET" \
--server-side-encryption-configuration file://encryption.jsonThe default applies to new uploads only. Objects already in an older bucket keep their old encryption until you copy them over themselves. Upload the test file without asking for any encryption, and look at what S3 did:
aws s3api put-object --bucket "$BUCKET" --key hello.txt --body hello.txt
aws s3api head-object --bucket "$BUCKET" --key hello.txt \
--query '{Encryption: ServerSideEncryption, Key: SSEKMSKeyId, BucketKey: BucketKeyEnabled}'Check it worked
head-object shows "Encryption": "aws:kms", a Key equal to the ARN you echoed, and "BucketKey": true.
Step 5 · Turn on versioning
Versioning keeps every earlier copy of an object when it is overwritten or deleted, so a bad deploy or a mistaken rm can be undone. Each version is billed as a full object, so pair it with a lifecycle rule that removes old versions after a while. Once a bucket has versioning, it can be suspended but never returned to unversioned.
aws s3api put-bucket-versioning --bucket "$BUCKET" \
--versioning-configuration Status=Enabled
cat > lifecycle.json <<'JSON'
{
"Rules": [
{
"ID": "expire-old-versions",
"Status": "Enabled",
"Filter": {},
"NoncurrentVersionExpiration": { "NoncurrentDays": 30 }
}
]
}
JSON
aws s3api put-bucket-lifecycle-configuration --bucket "$BUCKET" \
--lifecycle-configuration file://lifecycle.jsonChange the file and upload it again, then list its versions:
echo "second version" >> hello.txt
aws s3api put-object --bucket "$BUCKET" --key hello.txt --body hello.txt
aws s3api list-object-versions --bucket "$BUCKET" --prefix hello.txt \
--query 'Versions[].{Version: VersionId, Latest: IsLatest}'Check it worked
aws s3api get-bucket-versioning --bucket "$BUCKET" shows "Status": "Enabled". The version list has two entries for hello.txt, and only one has "Latest": true. The first upload was made before versioning, so its version ID is null.
Step 6 · Write the bucket policy
The bucket policy holds three Deny statements. A Deny beats any Allow anywhere, including your own administrator's, so these rules hold whatever IAM policies say:
cat > bucket-policy.json <<JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyRequestsWithoutTLS",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::$BUCKET",
"arn:aws:s3:::$BUCKET/*"
],
"Condition": {
"Bool": { "aws:SecureTransport": "false" }
}
},
{
"Sid": "DenyEncryptionWithoutOurKey",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::$BUCKET/*",
"Condition": {
"Null": {
"s3:x-amz-server-side-encryption": "false",
"s3:x-amz-server-side-encryption-aws-kms-key-id": "true"
}
}
},
{
"Sid": "DenyOtherKmsKeys",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::$BUCKET/*",
"Condition": {
"Null": { "s3:x-amz-server-side-encryption-aws-kms-key-id": "false" },
"StringNotEquals": { "s3:x-amz-server-side-encryption-aws-kms-key-id": "$KEY_ARN" }
}
}
]
}
JSON
jq -e . bucket-policy.json > /dev/null && echo "policy is valid JSON"Read each statement against a real upload:
- DenyRequestsWithoutTLS covers every action on the bucket and its objects.
aws:SecureTransportisfalseonly for plain HTTP, so HTTPS requests pass through. - DenyEncryptionWithoutOurKey catches an upload that names an encryption type but no KMS key. Inside one
Nullblock both tests must be true: the encryption header is present, and the key header is absent. That covers a client asking forAES256(SSE-S3), and also one asking foraws:kmswith no key, which S3 would otherwise encrypt with the AWS managed keyaws/s3rather than yours. - DenyOtherKmsKeys catches an upload that names a KMS key that is not yours.
- An upload with no encryption headers at all matches none of them, and the default encryption from the last step applies your key. That is why the policy does not simply demand the header: the AWS CLI, most SDKs and AWS services that deliver logs to buckets do not send it.
Attach the policy. BlockPublicPolicy would refuse it if it granted public access, but it only denies:
aws s3api put-bucket-policy --bucket "$BUCKET" --policy file://bucket-policy.jsonNow try the three cases. An upload that asks for SSE-S3 must be refused:
if aws s3api put-object --bucket "$BUCKET" --key wrong-key.txt --body hello.txt \
--server-side-encryption AES256; then
echo "the upload was allowed, check the policy"; false
fiAn upload that names your key, and a listing over plain HTTP:
aws s3api put-object --bucket "$BUCKET" --key right-key.txt --body hello.txt \
--server-side-encryption aws:kms --ssekms-key-id "$KEY_ARN"
aws s3 ls "s3://$BUCKET" --endpoint-url "http://s3.$AWS_REGION.amazonaws.com"Check it worked
The AES256 upload fails with AccessDenied, so the if prints nothing. The upload that names your key succeeds and returns an ETag. The listing over http:// fails with AccessDenied, while aws s3 ls "s3://$BUCKET" (HTTPS, the default) still lists hello.txt. aws s3api get-bucket-policy --bucket "$BUCKET" --query Policy --output text | jq -r '.Statement[].Sid' prints the three statement names.
Step 7 · List who can reach the bucket
Access to this bucket can come from four places: the bucket policy, ACLs, the KMS key policy, and IAM policies in your account. Check each.
S3 judges whether the bucket policy makes the bucket public:
aws s3api get-bucket-policy-status --bucket "$BUCKET"The bucket policy has no Allow statements, so it grants nothing to anyone outside your account:
aws s3api get-bucket-policy --bucket "$BUCKET" --query Policy --output text \
| jq '[.Statement[] | select(.Effect == "Allow")] | length'ACLs are off, so the bucket ACL shows only your account:
aws s3api get-bucket-acl --bucket "$BUCKET" \
--query 'Grants[].[Grantee.Type, Permission]' --output textThe key policy decides who can decrypt. The default policy names your account root, which hands the decision to IAM policies in your account:
aws kms get-key-policy --key-id "$KEY_ARN" --policy-name default \
--query Policy --output text | jq '.Statement[].Principal'So the full list of who can read objects is: principals in your account whose IAM policies allow both s3:GetObject on the bucket and kms:Decrypt on the key, over HTTPS. /tutorials/understand-aws-iam-users-groups-and-roles shows how to list what each principal can do.
IAM Access Analyzer checks this for you across all buckets and reports any bucket shared outside the account. If your account has an analyzer, list its findings for S3 (replace <analyzer-arn> with the ARN the first command prints):
aws accessanalyzer list-analyzers --query 'analyzers[].arn'
aws accessanalyzer list-findings --analyzer-arn <analyzer-arn> \
--filter '{"resourceType": {"eq": ["AWS::S3::Bucket"]}}'Check it worked
get-bucket-policy-status shows "IsPublic": false. The Allow count is 0. The ACL shows a single line, CanonicalUser FULL_CONTROL. The key policy principal is arn:aws:iam::<your-account>:root. Access Analyzer lists no active finding for this bucket.
Step 8 · Audit the bucket with a script
Settings drift. Someone loosens one to fix an urgent problem and forgets to put it back. A short script that checks every setting from this tutorial lets you re-check any bucket in seconds, or run it on a schedule:
cat > audit-bucket.sh <<'SH'
#!/usr/bin/env bash
# Usage: ./audit-bucket.sh <bucket-name>
# Checks the lock-down settings on one S3 bucket. Exits 1 if any check fails.
set -uo pipefail
BUCKET="$1"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
FOUR='[BlockPublicAcls,IgnorePublicAcls,BlockPublicPolicy,RestrictPublicBuckets]'
FAILS=0
check() {
# check <label> <actual> <expected>
if [ "$2" = "$3" ]; then
echo "PASS $1"
else
echo "FAIL $1 (found: ${2:-nothing})"
FAILS=$((FAILS + 1))
fi
}
check "account blocks public access" \
"$(aws s3control get-public-access-block --account-id "$ACCOUNT_ID" \
--query "PublicAccessBlockConfiguration.$FOUR" --output text 2>/dev/null | tr -s '\t' ' ')" \
"True True True True"
check "bucket blocks public access" \
"$(aws s3api get-public-access-block --bucket "$BUCKET" \
--query "PublicAccessBlockConfiguration.$FOUR" --output text 2>/dev/null | tr -s '\t' ' ')" \
"True True True True"
check "ACLs are disabled" \
"$(aws s3api get-bucket-ownership-controls --bucket "$BUCKET" \
--query 'OwnershipControls.Rules[0].ObjectOwnership' --output text 2>/dev/null)" \
"BucketOwnerEnforced"
check "policy denies requests without TLS" \
"$(aws s3api get-bucket-policy --bucket "$BUCKET" --query Policy --output text 2>/dev/null \
| jq -r '[.Statement[] | select(.Effect == "Deny" and .Condition.Bool["aws:SecureTransport"] == "false")] | length > 0' 2>/dev/null)" \
"true"
check "policy is not public" \
"$(aws s3api get-bucket-policy-status --bucket "$BUCKET" \
--query PolicyStatus.IsPublic --output text 2>/dev/null)" \
"False"
check "default encryption is SSE-KMS with a bucket key" \
"$(aws s3api get-bucket-encryption --bucket "$BUCKET" \
--query 'ServerSideEncryptionConfiguration.Rules[0].[ApplyServerSideEncryptionByDefault.SSEAlgorithm,BucketKeyEnabled]' \
--output text 2>/dev/null | tr -s '\t' ' ')" \
"aws:kms True"
check "versioning is on" \
"$(aws s3api get-bucket-versioning --bucket "$BUCKET" --query Status --output text 2>/dev/null)" \
"Enabled"
echo "$((7 - FAILS)) of 7 checks passed"
[ "$FAILS" -eq 0 ]
SH
chmod +x audit-bucket.sh
./audit-bucket.sh "$BUCKET"Every aws call sends its errors to /dev/null, so a missing setting shows up as FAIL ... (found: nothing) rather than a stack of messages. The script only reads; it changes nothing. To check all your buckets, loop over aws s3api list-buckets --query 'Buckets[].Name' --output text. Expect some older buckets to fail on encryption or versioning: decide for each whether it needs them, rather than switching everything on blindly.
Check it worked
The script prints seven PASS lines and 7 of 7 checks passed, and echo $? straight after it prints 0. To see a failure, run aws s3api put-bucket-versioning --bucket "$BUCKET" --versioning-configuration Status=Suspended, run the script again (it reports FAIL versioning is on (found: Suspended) and 6 of 7 checks passed), then set the status back to Enabled.
Step 9 · Clean up
Keep account-level Block Public Access on; it protects every bucket you create from now on. Remove the rest.
A versioned bucket can only be deleted once every version and delete marker in it is gone, and deleting versions is permanent. The first lines stop if BUCKET is not the demo bucket, so check the name before you run it. delete-objects takes up to 1,000 keys per call, which is plenty here:
cd ~/locked-demo
case "$BUCKET" in
locked-demo-*) echo "Deleting everything in $BUCKET" ;;
*) echo "BUCKET is not the demo bucket, stopping"; false ;;
esac
aws s3api list-object-versions --bucket "$BUCKET" --output json \
| jq '{Objects: ([.Versions[]?, .DeleteMarkers[]?] | map({Key, VersionId})), Quiet: true}' > delete.json
aws s3api delete-objects --bucket "$BUCKET" --delete file://delete.json
aws s3api delete-bucket --bucket "$BUCKET"A KMS key cannot be deleted at once. Schedule it for the shortest waiting period, seven days; during that time it cannot be used and is not billed, and you can still cancel. ${KEY_ARN##*/} is the key ID, the part of the ARN after the last /:
aws kms delete-alias --alias-name alias/locked-demo
aws kms schedule-key-deletion --key-id "${KEY_ARN##*/}" --pending-window-in-days 7
cd ~
rm -rf ~/locked-demoCheck it worked
aws s3api head-bucket --bucket "$BUCKET" fails with a 404 (Not Found). aws kms describe-key --key-id "$KEY_ARN" --query KeyMetadata.KeyState prints "PendingDeletion", and ~/locked-demo is gone.
Next steps
- Give someone a single file from a private bucket for a limited time: share private S3 files with presigned URLs.
- Serve a website from a bucket that stays private, with CloudFront as the only reader: host a static site on S3 and CloudFront.
- Work out which people and apps in your account pass the IAM half of the check: understand AWS IAM users, groups and roles.
- Sign in with short-lived credentials instead of access keys: set up the AWS CLI with SSO and named profiles.
Related tutorials
- Write, test and deploy an AWS Lambda function in Node.jsYou will have a tested Node.js 26 function running on AWS Lambda with its own logs-only role, tuned memory, timeout and environment variables, and a published version behind a live alias you can move forward or roll back.
- Understand AWS VPCs: subnets, route tables, gateways and NATYou will have built a two-zone VPC with public and private subnets, an internet gateway, a NAT gateway and a free S3 endpoint using the AWS CLI, read every route table to see which subnets are public and why, and then deleted it all.
- Share private S3 files safely with presigned URLsYou will keep an S3 bucket private and still let browsers download and upload files through short-lived presigned URLs, with type and size limits, CORS and logs that never hold a working link.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials