agent: |
RtdQuZz6wlulVQbBHTjVCheck which buckets allow AWS S3 Bucket Public Read Access
Check which buckets allow AWS S3 Bucket Public Read Access
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
The task involves scanning AWS S3 buckets to detect any that permit public read access, highlighting potential vulnerabilities in data privacy and security.
inputs
outputs
import boto3
from botocore.exceptions import ClientError, NoCredentialsError, BotoCoreError
import json
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def is_read_public(bucket_policy):
"""
Determines if the bucket policy allows public read access.
"""
try:
policy_document = json.loads(bucket_policy['Policy'])
except json.JSONDecodeError:
print("Error parsing the bucket policy JSON.")
return False
for statement in policy_document.get('Statement', []):
actions = statement.get('Action', [])
actions = [actions] if isinstance(actions, str) else actions
principals = statement.get('Principal', {})
# Checking if the principal is set to '*' (public access)
is_public_principal = principals == '*' or principals.get('AWS') == '*'
# Checking for 's3:Get*' or 's3:*' actions
public_read_actions = any(action in ['s3:Get*', 's3:*'] or action.startswith('s3:Get') for action in actions)
if is_public_principal and public_read_actions:
return True
return False
def is_acl_public_read(bucket_acl):
"""
Determines if the bucket ACL allows public read access.
"""
for grant in bucket_acl['Grants']:
if grant['Grantee'].get('Type') == 'Group' and grant['Grantee'].get('URI') == 'http://acs.amazonaws.com/groups/global/AllUsers':
if 'READ' in grant['Permission']:
return True
return False
def check_s3_buckets_public_read():
"""
Checks all S3 buckets in the account to ensure they do not allow public read access.
"""
try:
s3 = boto3.client('s3',aws_access_key_id=access_key,aws_secret_access_key=secret_key)
buckets = s3.list_buckets().get('Buckets', [])
if not buckets:
print("No S3 buckets found in the account.")
return
for bucket in buckets:
bucket_name = bucket['Name']
is_compliant = True
# Check block public access settings
try:
public_access_block = s3.get_public_access_block(Bucket=bucket_name)
if not public_access_block['PublicAccessBlockConfiguration'].get('BlockPublicAcls', False):
print(f"Bucket '{bucket_name}' is non-compliant: Public Access Block allows public read.")
is_compliant = False
except ClientError as e:
if e.response['Error']['Code'] != 'NoSuchPublicAccessBlockConfiguration':
raise
# Check the bucket policy
try:
bucket_policy = s3.get_bucket_policy(Bucket=bucket_name)
if is_read_public(bucket_policy):
print(f"Bucket '{bucket_name}' is non-compliant: Policy allows public read access.")
is_compliant = False
except ClientError as e:
if e.response['Error']['Code'] != 'NoSuchBucketPolicy':
raise
# Check bucket ACL
try:
bucket_acl = s3.get_bucket_acl(Bucket=bucket_name)
if is_acl_public_read(bucket_acl):
print(f"Bucket '{bucket_name}' is non-compliant: ACL allows public read access.")
is_compliant = False
except ClientError:
raise
if is_compliant:
print(f"Bucket '{bucket_name}' is compliant: No public read access detected.")
print("Public read access check complete for all S3 buckets.")
except NoCredentialsError:
print("No AWS credentials found. Please configure your credentials.")
except BotoCoreError as e:
print(f"An error occurred accessing AWS S3 service: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
check_s3_buckets_public_read()
context.skip_sub_tasks=True
copied
- 1Q6GwB4XEmKvA7IjX1TxcEnforce S3 Bucket Read Protection using Public Access Block Settings
1
Enforce S3 Bucket Read Protection using Public Access Block Settings
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task strengthens data security by restricting public read access to specified AWS S3 buckets. It updates Block Public Access settings and ACLs, ensuring data confidentiality. This action aligns with security compliance standards to protect sensitive information.
inputsoutputsimport boto3 from botocore.exceptions import ClientError, NoCredentialsError, BotoCoreError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] def disable_public_write_access(bucket_name): """ Disables public write access for a specified S3 bucket by updating Block Public Access settings and ACL. """ s3 = boto3.client('s3',aws_access_key_id=access_key,aws_secret_access_key=secret_key) # Update Block Public Access settings to block public ACLs try: s3.put_public_access_block( Bucket=bucket_name, PublicAccessBlockConfiguration={ 'BlockPublicAcls': True, 'IgnorePublicAcls': True, 'BlockPublicPolicy': True, 'RestrictPublicBuckets': True } ) print(f"Updated Block Public Access settings for '{bucket_name}'.") except ClientError as e: print(f"Failed to update Block Public Access settings for '{bucket_name}': {e}") raise try: if bucket_name: #bucket_name = 'your-bucket-name' disable_public_write_access(bucket_name) else: print("Please provide a bucket name to restrict public access") except NoCredentialsError: print("No AWS credentials found. Please configure your credentials.") except BotoCoreError as e: print(f"An error occurred accessing AWS S3 service: {e}") except Exception as e: print(f"An unexpected error occurred: {e}")copied1