#!/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_check24="2.4,2.04"
CHECK_TITLE_check24="[check24] Ensure CloudTrail trails are integrated with CloudWatch Logs (Scored)"
CHECK_SCORED_check24="SCORED"
CHECK_TYPE_check24="LEVEL1"
CHECK_ALTERNATE_check204="check24"

check24(){
  # "Ensure CloudTrail trails are integrated with CloudWatch Logs (Scored)"
  TRAILS_AND_REGIONS=$($AWSCLI cloudtrail describe-trails $PROFILE_OPT --region $REGION --query 'trailList[*].{Name:Name, HomeRegion:HomeRegion}' --output text | tr "	" ',')
  if [[ $TRAILS_AND_REGIONS ]];then
    for reg_trail in $TRAILS_AND_REGIONS;do
      trail=$(echo $reg_trail | cut -d',' -f2)
      TRAIL_REGION=$(echo $reg_trail | cut -d',' -f1)
      LATESTDELIVERY_TIMESTAMP=$($AWSCLI cloudtrail get-trail-status --name $trail $PROFILE_OPT --region $TRAIL_REGION --query 'LatestCloudWatchLogsDeliveryTime' --output text|grep -v None)
      if [[ ! $LATESTDELIVERY_TIMESTAMP ]];then
        textFail "$trail trail is not logging in the last 24h or not configured (it is in $TRAIL_REGION)"
      else
        LATESTDELIVERY_DATE=$(timestamp_to_date $LATESTDELIVERY_TIMESTAMP)
        HOWOLDER=$(how_older_from_today $LATESTDELIVERY_DATE)
        if [ $HOWOLDER -gt "1" ];then
          textFail "$trail trail is not logging in the last 24h or not configured (it is in $TRAIL_REGION)"
        else
          textPass "$trail trail has been logging during the last 24h (it is in $TRAIL_REGION)"
        fi
      fi
    done
  else
    textFail "No CloudTrail trails found!"
  fi
}
