boto3 aws check if s3 bucket is encrypted

时间:2019-04-17 01:53:44

标签: python amazon-web-services encryption boto3

I have the following code posted below which gets all the s3 bucket list on aws and I am trying to write code that checks if the buckets are encrypted in python but I am having trouble figuring out how to do that. Can anyone tell me how to modify my code to do that. I tried online examples and looked at the documentation.

my code is: from future import print_function import boto3 import os

 os.environ['AWS_DEFAULT_REGION'] = "us-east-1"
 # Create an S3 client
 s3 = boto3.client('s3')
 # Call S3 to list current buckets

 response = s3.list_buckets()

 # Get a list of all bucket names from the response
 buckets = [bucket['Name'] for bucket in response['Buckets']]

 # Print out the bucket list
 print("Bucket List: %s" % buckets)

Tried the following codes but they don't work:

 s3 = boto3.resource('s3')
 bucket = s3.Bucket('my-bucket-name')
 for obj in bucket.objects.all():
     key = s3.Object(bucket.name, obj.key)
     print key.server_side_encryption

and

 #!/usr/bin/env python
 import boto3

 s3_client = boto3.client('s3')
 head = s3_client.head_object(
     Bucket="<S3 bucket name>",
     Key="<S3 object key>"
 )
 if 'ServerSideEncryption' in head:
     print head['ServerSideEncryption']

1 个答案:

答案 0 :(得分:1)

首先值得了解有关S3和加密的一些知识。

  1. 在S3存储桶上启用默认加密时,实际上是在存储桶上配置服务器端加密配置规则,该规则将导致S3在配置规则后对上传到存储桶的每个对象进行加密。
  2. 与#1无关,您可以将S3存储桶策略应用于存储桶,拒绝上传任何未加密的对象。这样可以防止您添加未加密的数据,但不会自动加密任何内容。
  3. 您可以逐个对象地加密上传内容;加密不必在存储桶范围内进行。

因此,找出一种存储桶属于#1类(将自动加密上传到其中的任何内容)的一种方法,您可以执行以下操作:

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')

response = s3.list_buckets()

for bucket in response['Buckets']:
  try:
    enc = s3.get_bucket_encryption(Bucket=bucket['Name'])
    rules = enc['ServerSideEncryptionConfiguration']['Rules']
    print('Bucket: %s, Encryption: %s' % (bucket['Name'], rules))
  except ClientError as e:
    if e.response['Error']['Code'] == 'ServerSideEncryptionConfigurationNotFoundError':
      print('Bucket: %s, no server-side encryption' % (bucket['Name']))
    else:
      print("Bucket: %s, unexpected error: %s" % (bucket['Name'], e))

这将导致如下输出:

Bucket: mycats, no server-side encryption
Bucket: mydogs, no server-side encryption
Bucket: mytaxreturn, Encryption: [{'ApplyServerSideEncryptionByDefault': {'SSEAlgorithm': 'AES256'}}]