Programmatically set Public Block on AWS S3 Buckets

Recently, we have all seen many reports of AWS buckets that contained private data that were misconfigured and fully open to the public. Whether the result is slight embarrassment or a serious exfiltration of data, the risk of a misconfigured bucket can be mitigated fairly easily.

Amazon S3 buckets can be setup to allow or block public access so that a bad policy or permission does not expose your data. The settings are available in the Web gui and in the API. This little bit of code will illustrate how to use boto3 to manipulate the Public Block Settings on your buckets.

Do NOT run this code in any production environment without understanding what will happen

import boto3

def main():
    # Create the boto Session from the profile stored on the host
    mySess = boto3.Session(profile_name='myawsprofile')
    s3client = mySess.client('s3')
    # Get the list of all your buckets
    allbuckets = s3client.list_buckets()
    # Iterate over the list 
    for bucket in allbuckets['Buckets']:
        try:
            # This will set the public block settings
            s3client.put_public_access_block(
                Bucket=bucket['Name'],
                PublicAccessBlockConfiguration={
                    'BlockPublicAcls': True,
                    'IgnorePublicAcls': True,
                    'BlockPublicPolicy': True,
                    'RestrictPublicBuckets': False
                }
            )
        except:
            # How to handle an error goes here
            pass

if __name__== "__main__":
    main()

More information on this can be found in the Boto3 docs for put_public_block_access.

Tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
2 × 21 =