forked from mtusi2026/mtusi2026lab4
40 lines
1.6 KiB
Python
40 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Verify anonymous S3 listing and direct object download are denied."""
|
|
import os
|
|
import uuid
|
|
|
|
import boto3
|
|
from botocore import UNSIGNED
|
|
from botocore.config import Config
|
|
from botocore.exceptions import ClientError
|
|
|
|
endpoint=os.getenv('S3_ENDPOINT','http://rustfs:9000')
|
|
bucket=os.getenv('S3_BUCKET','messenger-attachments')
|
|
region=os.getenv('S3_REGION','us-east-1')
|
|
cfg=Config(s3={'addressing_style':'path'})
|
|
signed=boto3.client('s3',endpoint_url=endpoint,region_name=region,
|
|
aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],
|
|
aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],config=cfg)
|
|
anonymous=boto3.client('s3',endpoint_url=endpoint,region_name=region,
|
|
config=Config(signature_version=UNSIGNED,s3={'addressing_style':'path'}))
|
|
key='attachments/private-check/'+uuid.uuid4().hex
|
|
|
|
def denied(operation, **kwargs):
|
|
try:
|
|
response=operation(**kwargs)
|
|
body=response.get('Body')
|
|
if body: body.close()
|
|
except ClientError as exc:
|
|
status=exc.response.get('ResponseMetadata',{}).get('HTTPStatusCode')
|
|
if status in (401,403): return status
|
|
raise
|
|
raise AssertionError('anonymous S3 request unexpectedly succeeded')
|
|
|
|
try:
|
|
signed.put_object(Bucket=bucket,Key=key,Body=b'private-bucket-check')
|
|
list_status=denied(anonymous.list_objects_v2,Bucket=bucket,Prefix='attachments/',MaxKeys=1)
|
|
get_status=denied(anonymous.get_object,Bucket=bucket,Key=key)
|
|
print('PASS: anonymous ListBucket denied with HTTP %d; direct GetObject denied with HTTP %d' % (list_status,get_status))
|
|
finally:
|
|
signed.delete_object(Bucket=bucket,Key=key)
|