#!/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_extra716="7.16"
CHECK_TITLE_extra716="[extra716] Check if Elasticsearch Service domains allow open access (Not Scored) (Not part of CIS benchmark)"
CHECK_SCORED_extra716="NOT_SCORED"
CHECK_TYPE_extra716="EXTRA"
CHECK_ALTERNATE_check716="extra716"

extra716(){
  # "Check if Elasticsearch Service domains allow open access (Not Scored) (Not part of CIS benchmark)"
  for regx in $REGIONS; do
    LIST_OF_DOMAINS=$($AWSCLI es list-domain-names $PROFILE_OPT --region $regx --query DomainNames --output text)
    if [[ $LIST_OF_DOMAINS ]]; then
      for domain in $LIST_OF_DOMAINS;do
        CHECK_IF_MEMBER_OF_VPC=$($AWSCLI es describe-elasticsearch-domain-config --domain-name $domain $PROFILE_OPT --region $regx --query DomainConfig.VPCOptions.Options.VPCId --output text|grep -v ^None)
        if [[ ! $CHECK_IF_MEMBER_OF_VPC ]];then
          TEMP_POLICY_FILE=$(mktemp -t prowler-${ACCOUNT_NUM}-es-domain.policy.XXXXXXXXXX)
          $AWSCLI es describe-elasticsearch-domain-config --domain-name $domain $PROFILE_OPT --region $regx --query DomainConfig.AccessPolicies.Options --output text > $TEMP_POLICY_FILE 2> /dev/null
          # check if the policy has Principal as *
          CHECK_ES_DOMAIN_ALLUSERS_POLICY=$(cat $TEMP_POLICY_FILE | jq -r '. | .Statement[] | select(.Effect == "Allow" and (((.Principal|type == "object") and .Principal.AWS == "*") or ((.Principal|type == "string") and .Principal == "*")) and .Condition == null)')
          if [[ $CHECK_ES_DOMAIN_ALLUSERS_POLICY ]];then
            textFail "$regx: $domain policy \"may\" allow Anonymous users to perform actions (Principal: \"*\")" "$regx"
          else
            textPass "$regx: $domain is not open" "$regx"
          fi
        else
          textPass "$regx: $domain is in a VPC" "$regx"
        fi
        rm -f $TEMP_POLICY_FILE
      done
    else
      textInfo "$regx: No Elasticsearch Service domain found" "$regx"
    fi
  done
}
