#!/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_extra78="7.8"
CHECK_TITLE_extra78="[extra78] Ensure there are no Public Accessible RDS instances"
CHECK_SCORED_extra78="NOT_SCORED"
CHECK_CIS_LEVEL_extra78="EXTRA"
CHECK_SEVERITY_extra78="Critical"
CHECK_ASFF_RESOURCE_TYPE_extra78="AwsRdsDbInstance"
CHECK_ALTERNATE_extra708="extra78"
CHECK_ALTERNATE_check78="extra78"
CHECK_ALTERNATE_check708="extra78"
CHECK_SERVICENAME_extra78="rds"
CHECK_RISK_extra78='Publicly accessible databases could expose sensitive data to bad actors.'
CHECK_REMEDIATION_extra78='Using an AWS Config rule check for RDS public instances periodically and check there is a business reason for it.'
CHECK_DOC_extra78='https://docs.amazonaws.cn/en_us/config/latest/developerguide/rds-instance-public-access-check.html'
CHECK_CAF_EPIC_extra78='Data Protection'

extra78(){
  # "Ensure there are no Public Accessible RDS instances "
  for regx in $REGIONS; do
    LIST_OF_RDS_PUBLIC_INSTANCES=$($AWSCLI rds describe-db-instances $PROFILE_OPT --region $regx --query 'DBInstances[?PubliclyAccessible==`true` && DBInstanceStatus==`"available"`].[DBInstanceIdentifier,Endpoint.Address]' --output text 2>&1)
    if [[ $(echo "$LIST_OF_RDS_PUBLIC_INSTANCES" | grep AccessDenied) ]]; then
      textInfo "$regx: Access Denied Trying to describe DB instances" "$regx"
      continue
    fi
    if [[ $LIST_OF_RDS_PUBLIC_INSTANCES ]];then
      while read -r rds_instance;do
        RDS_NAME=$(echo $rds_instance | awk '{ print $1; }')
        RDS_DNSNAME=$(echo $rds_instance | awk '{ print $2; }')
        textFail "$regx: RDS instance: $RDS_NAME at $RDS_DNSNAME is set as Publicly Accessible!" "$regx" "$RDS_NAME"
      done <<< "$LIST_OF_RDS_PUBLIC_INSTANCES"
      else
        textPass "$regx: no Publicly Accessible RDS instances found" "$regx" "$RDS_NAME"
    fi
  done
}
