Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boto: Find if bucket is public or private

Tags:

boto3

I don't find a way to easily know if my AWS S3 buckets are public or private.

I was expecting to do list_bucket_response = s3client.list_buckets() and directly know if the bucket is publicly accessible or not. I've came across https://jgreenemi.com/how-to-check-if-your-s3-buckets-allow-public-read-acls/ but in my case when I list buckets I don't get an URI.

I also tried s3client.get_bucket_acl(Bucket=bucket_name) without success.

like image 445
nono Avatar asked Dec 31 '22 11:12

nono


2 Answers

You have to evaluate 3 different conditions to check whether a bucket is public or not:

  • Policies
  • ACLs
  • Block public access setting

According to this guide:

  1. Use get_public_access_block() method to check if block public access option is set.
response = s3client.get_public_access_block(Bucket='bucket_name')

If both of the following are set to true, then the bucket is not public:

response['PublicAccessBlockConfiguration']['BlockPublicAcls']
response['PublicAccessBlockConfiguration']['BlockPublicPolicy']
  1. Use get_bucket_policy_status() method to check if policies allow public access.

get_bucket_policy_status

Retrieves the policy status for an Amazon S3 bucket, indicating whether the bucket is public

response = s3_client.get_bucket_policy_status(Bucket='bucket_name')

The bucket is public if the following is true:

response['PolicyStatus']['IsPublic']
  1. Check ACLs to see if grantee is AllUsers or AuthenticatedUsers groups.
response = s3client.get_bucket_acl(Bucket='bucket_name')

The bucket is public if the ACL grants any permissions to members of the predefined AllUsers or AuthenticatedUsers groups.

Grantee (response['Grants'][*]['Grantee']):

  • Type: Group
  • URI:
    • http://acs.amazonaws.com/groups/global/AuthenticatedUsers
    • http://acs.amazonaws.com/groups/global/AllUsers

You can further evaluate object ACLs if required.

like image 158
Vikyol Avatar answered Jan 13 '23 11:01

Vikyol


Actually get_bucket_policy_status will throw an exception if you turned off public access I found this piece of code works well

    try:
        access = s3.get_public_access_block(Bucket=bucket['Name'])
        print (access)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
            print('\t no Public Access')
        else:
            print("unexpected error: %s" % (e.response))
like image 40
codaddict Avatar answered Jan 13 '23 12:01

codaddict