#!/usr/bin/env bash
# Prowler - the handy cloud security tool (copyright 2019) by Toni de la Fuente
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
CHECK_ID_extra7139="7.139"
CHECK_TITLE_extra7139="[extra7139] There are High severity GuardDuty findings "
CHECK_SCORED_extra7139="NOT_SCORED"
CHECK_CIS_LEVEL_extra7139="EXTRA"
CHECK_SEVERITY_extra7139="High"
CHECK_ASFF_RESOURCE_TYPE_extra7139="AwsGuardDutyDetector"
CHECK_ALTERNATE_check7139="extra7139"
CHECK_SERVICENAME_extra7139="guardduty"
CHECK_RISK_extra7139='If critical findings are not addressed threats can spread in the environment.'
CHECK_REMEDIATION_extra7139='Review and remediate critical GuardDuty findings as quickly as possible.'
CHECK_DOC_extra7139='https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html'
CHECK_CAF_EPIC_extra7139='Incident Response'
extra7139(){
  
  for regx in $REGIONS; do
    DETECTORS_LIST=""
    DETECTORS_LIST=$($AWSCLI guardduty list-detectors --query DetectorIds $PROFILE_OPT --region $regx --output text 2>&1)
    if [[ $(echo "$DETECTORS_LIST" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$regx: Access Denied trying to list detectors" "$regx"
        continue
    fi
    if [[ $DETECTORS_LIST ]];then
      for DETECTOR in $DETECTORS_LIST;do
        FINDINGS_COUNT=""
        FINDINGS_COUNT=$($AWSCLI $PROFILE_OPT --region $regx --output text guardduty list-findings --detector-id $DETECTOR --finding-criteria '{"Criterion":{"severity": {"Eq":["8"]}, "service.archived": {"Eq": ["false"]}}}' 2> /dev/null | wc -l | xargs) # Severity LOW=2, MED=4, HIGH=8
          if [[ $FINDINGS_COUNT -gt 0 ]];then
            textFail "$regx: GuardDuty has $FINDINGS_COUNT high severity findings." "$regx"
          else
            textPass "$regx: GuardDuty has no high severity findings." "$regx"
          fi
      done
    else
      textInfo "$regx: No GuardDuty detectors found." "$regx"
    fi
  done
}