#!/usr/bin/env bash

# Prowler - the handy cloud security tool (c) by Toni de la Fuente
#
# This Prowler check is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
#
# You should have received a copy of the license along with this
# work. If not, see <http://creativecommons.org/licenses/by-nc-sa/4.0/>.

CHECK_ID_check23="2.3,2.03"
CHECK_TITLE_check23="[check23] Ensure the S3 bucket CloudTrail logs to is not publicly accessible (Scored)"
CHECK_SCORED_check23="SCORED"
CHECK_TYPE_check23="LEVEL1"
CHECK_ALTERNATE_check203="check23"

check23(){
  # "Ensure the S3 bucket CloudTrail logs to is not publicly accessible (Scored)"
  CLOUDTRAILBUCKET=$($AWSCLI cloudtrail describe-trails --query 'trailList[*].S3BucketName' --output text $PROFILE_OPT --region $REGION)
  if [[ $CLOUDTRAILBUCKET ]]; then
    for bucket in $CLOUDTRAILBUCKET;do
      CLOUDTRAILBUCKET_HASALLPERMISIONS=$($AWSCLI s3api get-bucket-acl --bucket $bucket --query 'Grants[?Grantee.URI==`http://acs.amazonaws.com/groups/global/AllUsers`]' $PROFILE_OPT --region $REGION --output text 2>&1)
      if [[ $(echo "$CLOUDTRAILBUCKET_HASALLPERMISIONS" | grep AccessDenied) ]]; then
        textFail "Access Denied Trying to Get Bucket Acl for $bucket"
        continue
      fi
      if [[ $CLOUDTRAILBUCKET_HASALLPERMISIONS ]]; then
        textFail "check your $bucket CloudTrail bucket ACL and Policy!"
      else
        textPass "Bucket $bucket is set correctly"
      fi
    done
  else
    textFail "No CloudTrail bucket found!"
  fi
}
