cloudtrail_status_check.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. import boto3
  3. def answer_no(x): return True if str(x).lower() in [
  4. '0', 'no', 'false'] else False
  5. def answer_yes(x): return True if str(x).lower() in [
  6. '1', 'yes', 'true'] else False
  7. def send_notifications(message):
  8. # TODO
  9. return True
  10. def is_bucket_not_public(bucket_name):
  11. s3 = boto3.client('s3')
  12. bucket_acl = s3.get_bucket_acl(Bucket=bucket_name)
  13. # If there is a permission attached with any value for AllUsers,
  14. # it means the bucket is public
  15. # We don't need to check if the permission any of
  16. # READ|WRITE|READ_ACP|WRITE_ACP|FULL_CONTROL
  17. for grantee in bucket_acl['Grants']:
  18. if grantee['Grantee']['Type'] == 'Group' \
  19. and grantee['Grantee']['URI'] == 'http://acs.amazonaws.com/groups/global/AllUsers':
  20. return False
  21. return True
  22. def lambda_handler(event, context):
  23. rc = 1
  24. message_body = 'Chekcing trails'
  25. print message_body
  26. cloudtrail = boto3.client('cloudtrail')
  27. trails = cloudtrail.describe_trails()
  28. for trail in trails['trailList']:
  29. notification = 'Checking ' + trail['Name']
  30. print notification
  31. message_body += notification + "\n"
  32. if trail['IsMultiRegionTrail'] \
  33. and ('KmsKeyId' in trail and trail['KmsKeyId'] != '') \
  34. and trail['IncludeGlobalServiceEvents'] \
  35. and trail['LogFileValidationEnabled']:
  36. notification = trail['Name'] + ' is OK'
  37. print notification
  38. message_body += notification + "\n"
  39. rc = 0
  40. else:
  41. notification = trail['Name'] + \
  42. ' does not match with the requirements'
  43. print notification
  44. message_body += notification + "\n"
  45. if not is_bucket_not_public(trail['S3BucketName']):
  46. rc = 1
  47. notification = trail['Name'] + \
  48. "\'s bucket has public access."
  49. print notification
  50. message_body += notification + "\n"
  51. if rc == 1 and ('DRY_RUN' in os.environ and answer_no(os.environ['DRY_RUN'])):
  52. send_notifications(message_body)
  53. exit(rc)
  54. # if __name__ == "__main__":
  55. # event = 1
  56. # context = 1
  57. # lambda_handler(event, context)