#!/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_check26="2.6,2.06"
CHECK_TITLE_check26="[check26] Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket (Scored)"
CHECK_SCORED_check26="SCORED"
CHECK_TYPE_check26="LEVEL1"
CHECK_ALTERNATE_check206="check26"

check26(){
  # "Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket (Scored)"

  CLOUDTRAILS=$($AWSCLI cloudtrail describe-trails $PROFILE_OPT --region "$REGION" --query 'trailList[*].Name' --output text| tr '\011' '\012' | awk -F: '{print $1}')

  if [[ $CLOUDTRAILS ]]; then
    for trail in $CLOUDTRAILS; do
      CLOUDTRAIL_ACCOUNT_ID=$($AWSCLI cloudtrail describe-trails $PROFILE_OPT --region "$REGION" --query 'trailList[*].TrailARN' --output text | tr '\011' '\012' | grep "$trail" | awk -F: '{ print $5 }'  | head -n 1)
      CLOUDTRAILBUCKET=$($AWSCLI cloudtrail describe-trails $PROFILE_OPT --region $REGION --query 'trailList[*].[Name, S3BucketName]' --output text  | tr '\011' ':' |  grep "$trail" | awk -F: '{ print $2 }' )

      if [[ $CLOUDTRAILBUCKET ]]; then
        bucket=$CLOUDTRAILBUCKET
        if [ "$CLOUDTRAIL_ACCOUNT_ID" == "$ACCOUNT_NUM" ]; then
          CLOUDTRAILBUCKET_LOGENABLED=$($AWSCLI s3api get-bucket-logging --bucket $bucket $PROFILE_OPT --region $REGION --query 'LoggingEnabled.TargetBucket' --output text 2>&1)
          if [[ $(echo "$CLOUDTRAILBUCKET_LOGENABLED" | grep AccessDenied) ]]; then
            textFail "Access Denied Trying to Get Bucket Logging for $bucket"
            continue
          fi
          if [[ $CLOUDTRAILBUCKET_LOGENABLED != "null" ]]; then
            textPass "Bucket access logging enabled in CloudTrail S3 bucket $bucket for $trail"
          else
            textFail "Bucket access logging is not enabled in CloudTrail S3 bucket $bucket for $trail"
          fi
        else
          textInfo "CloudTrail S3 bucket $bucket for trail $trail is not in current account"
        fi
      else
        textFail "CloudTrail bucket not found!"
      fi
    done

  else
    textFail "No CloudWatch group found and no CloudTrail bucket"
  fi
}
