#!/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_extra7146="7.146"
CHECK_TITLE_extra7146="[extra7146] Check if there is any unassigned Elastic IP"
CHECK_SCORED_extra7146="NOT_SCORED"
CHECK_CIS_LEVEL_extra7146="EXTRA"
CHECK_SEVERITY_extra7146="Low"
CHECK_ASFF_RESOURCE_TYPE_extra7146="AwsElasticIPs"
CHECK_ALTERNATE_check7146="extra7146"
CHECK_SERVICENAME_extra7146="ec2"
CHECK_RISK_extra7146='Unassigned Elastic IPs may result in extra cost'
CHECK_REMEDIATION_extra7146='Ensure Elastic IPs are not unassigned'
CHECK_DOC_extra7146='https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html'
CHECK_CAF_EPIC_extra7146='Infrastructure Security'

extra7146(){
  # "Check if there is any unassigned elastic ip (Not Scored) (Not part of CIS benchmark)"
  for regx in $REGIONS; do
    ELASTIC_IP_ADDRESSES=$($AWSCLI ec2 describe-addresses $PROFILE_OPT --region $regx --query Addresses --output json 2>&1)
    if [[ $(echo "$ELASTIC_IP_ADDRESSES" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$regx: Access Denied trying to describe addresses" "$regx"
        continue
    fi
    if [[ $ELASTIC_IP_ADDRESSES != [] ]]; then
      LIST_OF_ASSOCIATED_IPS=$(echo $ELASTIC_IP_ADDRESSES | jq -r '.[] | select(.AssociationId!=null) | .PublicIp')
      LIST_OF_UNASSOCIATED_IPS=$(echo $ELASTIC_IP_ADDRESSES | jq -r '.[] | select(.AssociationId==null) | .PublicIp')
      for ass_ip in $LIST_OF_ASSOCIATED_IPS; do
      textPass "$regx: Elastic IP $ass_ip is associated with an instance or network interface" "$regx" "$ass_ip"
      done
      for unass_ip in $LIST_OF_UNASSOCIATED_IPS; do
      textInfo "$regx: Elastic IP $unass_ip is not associated with any instance or network interface and it may incurr extra cost" "$regx" "$unass_ip"
      done
    else
      textInfo "$regx: No Elastic IPs found" "$regx"
    fi
  done
}
