#!/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_extra772="7.72"
CHECK_TITLE_extra772="[extra772] Check if elastic IPs are unused "
CHECK_SCORED_extra772="NOT_SCORED"
CHECK_CIS_LEVEL_extra772="EXTRA"
CHECK_SEVERITY_extra772="Low"
CHECK_ASFF_RESOURCE_TYPE_extra772="AwsEc2Eip"
CHECK_ALTERNATE_check772="extra772"
CHECK_SERVICENAME_extra772="ec2"
CHECK_RISK_extra772='You are charged by the hour for each Elastic IP address that are not attached to an EC2 instance .'
CHECK_REMEDIATION_extra772='If you don’t need an Elastic IP address; you can stop the charges by releasing the IP address.'
CHECK_DOC_extra772='https://aws.amazon.com/premiumsupport/knowledge-center/elastic-ip-charges/'
CHECK_CAF_EPIC_extra772='Infrastructure Security'

extra772(){
  for region in $REGIONS; do
    EIP_DUMP=$($AWSCLI ec2 describe-addresses ${PROFILE_OPT} --region $region --output json 2>&1)
    if [[ $(echo "$EIP_DUMP" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$regx: Access Denied trying to describe addresses" "$regx"
        continue
    fi 
    EIP_LIST=$(echo $EIP_DUMP | jq -r '.Addresses[].AllocationId')
    if [[ $EIP_LIST ]]; then
      for eip in $EIP_LIST; do
        ASSOCIATION_ID=$(echo $EIP_DUMP | jq -r --arg i "$eip" '.Addresses[]|select(.AllocationId==$i)|.AssociationId')
        if [[ "$ASSOCIATION_ID" == "null" ]]; then
          textFail "$region: EIP $eip is unused" "$region" "$eip"
        else
          textPass "$region: EIP $eip is used" "$region" "$eip"
        fi
      done
    else
      textInfo "$region: No Elastic IPs found" $region
    fi
  done
}
