#!/usr/bin/env bash

# Prowler - the handy cloud security tool (copyright 2018) 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_extra7101="7.101"
CHECK_TITLE_extra7101="[extra7101] Check if Amazon Elasticsearch Service (ES) domains have audit logging enabled"
CHECK_SCORED_extra7101="NOT_SCORED"
CHECK_CIS_LEVEL_extra7101="EXTRA"
CHECK_SEVERITY_extra7101="Low"
CHECK_ASFF_RESOURCE_TYPE_extra7101="AwsElasticsearchDomain"
CHECK_ALTERNATE_check7101="extra7101"
CHECK_SERVICENAME_extra7101="es"
CHECK_RISK_extra7101='If logs are not enabled; monitoring of service use and threat analysis is not possible.'
CHECK_REMEDIATION_extra7101='Make sure you are logging information about Amazon Elasticsearch Service operations.'
CHECK_DOC_extra7101='https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/audit-logs.html'
CHECK_CAF_EPIC_extra7101='Logging and Monitoring'

extra7101(){
  for regx in ${REGIONS}; do
    LIST_OF_DOMAINS=$("${AWSCLI}" es list-domain-names ${PROFILE_OPT} --region "${regx}" --query 'DomainNames[].DomainName' --output text 2>&1)
    if [[ $(echo "${LIST_OF_DOMAINS}" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "${regx}: Access Denied trying to list domain names" "${regx}"
        continue
    fi
    if [[ "${LIST_OF_DOMAINS}" ]]; then
      for domain in ${LIST_OF_DOMAINS}; do
        AUDIT_LOGS_ENABLED=$("${AWSCLI}" es describe-elasticsearch-domain-config --domain-name "${domain}" ${PROFILE_OPT} --region "${regx}" --query 'DomainConfig.LogPublishingOptions.Options.AUDIT_LOGS.Enabled' --output text 2>&1)
        if [[ $(echo "${AUDIT_LOGS_ENABLED}" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
            textInfo "${regx}: Access Denied trying to get ES domain config for ${domain}" "${regx}"
            continue
        fi
        if [[ $(tr '[:upper:]' '[:lower:]' <<< "${AUDIT_LOGS_ENABLED}") == "true" ]]; then
          textPass "${regx}: Amazon ES domain ${domain} AUDIT_LOGS enabled" "${regx}" "${domain}"
        else
          textFail "${regx}: Amazon ES domain ${domain} AUDIT_LOGS disabled!" "${regx}" "${domain}"
        fi
      done
    else
      textInfo "${regx}: No Amazon ES domain found" "${regx}"
    fi
  done
}
