Skip to content

Instantly share code, notes, and snippets.

@apolloclark
Last active January 27, 2023 08:10
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save apolloclark/7f805c503a3b4427955cabe93c6d824b to your computer and use it in GitHub Desktop.
Save apolloclark/7f805c503a3b4427955cabe93c6d824b to your computer and use it in GitHub Desktop.
Bash one-liner to find public facing AWS S3 buckets, and make them private

Command

aws s3api list-buckets --query 'Buckets[*].[Name]' --output text | xargs -I {} bash -c 'if [[ $(aws s3api get-bucket-acl --bucket {} --query '"'"'Grants[?Grantee.URI==`http://acs.amazonaws.com/groups/global/AllUsers` && Permission==`READ`]'"'"' --output text) ]]; then aws s3api put-bucket-acl --acl "private" --bucket {} ; fi'



1. List all of the user's buckets, and output the name, as text.

aws s3api list-buckets --query 'Buckets[*].[Name]' --output text

https://docs.aws.amazon.com/cli/latest/reference/s3api/list-buckets.html

2. Save the output of the previous command, call bash, substitute {} for the bucket name.

xargs -I {} bash -c '..'

http://man7.org/linux/man-pages/man1/xargs.1.html

3. Using the bucket name, check the ACL permissions, and see if it's public facing.

if [[ $(aws s3api get-bucket-acl --bucket {} --query '"'"'Grants[?Grantee.URI==`http://acs.amazonaws.com/groups/global/AllUsers` && Permission==`READ`]'"'"' --output text) ]]; then ...

https://docs.aws.amazon.com/cli/latest/reference/s3api/get-bucket-acl.html

4. Using the bucket name, lock down the ACL permissions to be private.

aws s3api put-bucket-acl --acl "private" --bucket {}

https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html

S3 bucket tutorial

https://gist.github.com/apolloclark/b3f60c1f68aa972d324b#s3

@ahpegasus
Copy link

I need similar operation to put bucket encryption i tried your method but i am getting json error

https://stackoverflow.com/questions/59203164/aws-s3-bucket-bulk-encryption-on-all-s3-buckets

@ahpegasus
Copy link

aws s3api list-buckets --query 'Buckets[*].[Name]' --output text | xargs -I {} bash -c 'aws s3api put-bucket-encryption --bucket {} --server-side-encryption-configuration '{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}''``

@anthonyclarka2
Copy link

This is great, thank you for sharing

@mitraed
Copy link

mitraed commented Feb 3, 2022

Thank you for this but the command you put at the top changes the configuration on the s3 bucket!
please mention that to avoid issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment