Skip to content

Instantly share code, notes, and snippets.

@andymotta
Last active December 9, 2017 03:07
Show Gist options
  • Save andymotta/d5622d1003e9db311e77d6421509d610 to your computer and use it in GitHub Desktop.
Save andymotta/d5622d1003e9db311e77d6421509d610 to your computer and use it in GitHub Desktop.
Compliance: Find S3 buckets with public access, send offending statements to SNS topic
#!/usr/bin/env python
import json
import boto3
import botocore
s3 = boto3.resource('s3')
client = boto3.client('s3')
sns = boto3.client('sns')
def lambda_handler(event, context):
offending = []
for bucket in s3.buckets.all():
try:
bucket_policy = client.get_bucket_policy(Bucket=bucket.name)
bucket_policy_j = json.loads(bucket_policy["Policy"])
for statement in bucket_policy_j["Statement"]:
if (statement["Effect"] == "Allow" and
statement["Principal"] == "*" ):
pretty_statement = json.dumps(statement, indent=4, sort_keys=True)
offending.append("%s: %s" % (bucket.name, pretty_statement))
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "NoSuchBucketPolicy":
pass
else:
print("Unexpected error on %s: %s" % (bucket.name, e))
if offending:
msg = '\n\n'.join(offending)
else:
msg = "Could not find any ops buckets granting public access"
response = sns.publish(
TopicArn='arn:aws:sns:us-west-2:000000000000:topic-name',
Message=msg,
Subject='S3 Public Access Granted'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment