#!/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.

# Checks that the correct mode (json-asff) has been specified if wanting to send check output to AWS Security Hub
# and that Security Hub is enabled in the chosen region
checkSecurityHubCompatibility(){

  local regx
  if [[ ! "${MODE}" =~ "json-asff" ]]; then
    echo -e "\n$RED ERROR!$NORMAL Output can only be sent to Security Hub when the output mode is json-asff, i.e. -M json-asff -S\n"
    EXITCODE=1
    exit $EXITCODE
  fi
  for regx in $REGIONS; do
    SECURITY_HUB_ENABLED=$($AWSCLI securityhub --region "$regx" $PROFILE_OPT describe-hub 2>/dev/null)
    if [[ -z "${SECURITY_HUB_ENABLED}" ]]; then
      if [[ -z "${PROWLER_PRODUCT_SUBSCRIPTION_ENABLED}" ]]; then
        echo -e "\n$RED ERROR!$NORMAL Security Hub is not enabled in $regx. Enable it running '$AWSCLI securityhub --region $regx $PROFILE_OPT enable-security-hub'. More info: https://github.com/prowler-cloud/prowler/#security-hub-integration\n"
        EXITCODE=1
        exit $EXITCODE
      fi
    else
      PROWLER_PRODUCT_SUBSCRIPTION_ENABLED=$($AWSCLI securityhub --region "$regx" $PROFILE_OPT list-enabled-products-for-import --output text | grep "prowler/prowler" )
      if [[ -z "${PROWLER_PRODUCT_SUBSCRIPTION_ENABLED}" ]]; then
        echo -e "\n$RED ERROR!$NORMAL Security Hub is enabled in $regx but Prowler integration does not accept findings. Enable it running '$AWSCLI securityhub --region $regx $PROFILE_OPT enable-import-findings-for-product --product-arn arn:aws:securityhub:$regx::product/prowler/prowler'. More info: https://github.com/prowler-cloud/prowler/#security-hub-integration\n"
        EXITCODE=1
        exit $EXITCODE
      fi
    fi
  done
}

resolveSecurityHubPreviousFails(){
  # Move previous check findings RecordState to ARCHIVED (as prowler didn't re-detect them)
    SH_TEMP_FOLDER="$PROWLER_DIR/SH-$ACCOUNT_NUM"
    if [[ ! -d $SH_TEMP_FOLDER ]]; then
      # this folder is deleted once the security hub update is completed
      mkdir "$SH_TEMP_FOLDER"
    fi
  for regx in $REGIONS; do
    REGION_FOLDER="$SH_TEMP_FOLDER/$regx"
    if [[ ! -d $REGION_FOLDER ]]; then
      mkdir "$REGION_FOLDER"
    fi
    local check="$1"
    NEW_TIMESTAMP=$(get_iso8601_timestamp)

    FILTER="{\"GeneratorId\":[{\"Value\": \"prowler-$check\",\"Comparison\":\"EQUALS\"}],\"RecordState\":[{\"Value\": \"ACTIVE\",\"Comparison\":\"EQUALS\"}],\"AwsAccountId\":[{\"Value\": \"$ACCOUNT_NUM\",\"Comparison\":\"EQUALS\"}]}"

    NEW_FINDING_FILE="$REGION_FOLDER/findings.json"
    NEW_FINDING_IDS=$(echo -n "${SECURITYHUB_NEW_FINDINGS_IDS[@]}" | jq -cRs 'split(" ")' > $NEW_FINDING_FILE)
    EXISTING_FILE="$REGION_FOLDER/existing.json"
    EXISTING_FINDINGS=$($AWSCLI securityhub --region "$regx" $PROFILE_OPT get-findings --filters "${FILTER}" > $EXISTING_FILE)

    SECURITY_HUB_PREVIOUS_FINDINGS=$(for id in $(comm -23 <(jq '[.Findings[].Id] | sort | .[]' $EXISTING_FILE) <(jq '[.[]] | sort | .[]' $NEW_FINDING_FILE));
      do
        jq --arg updated_at $NEW_TIMESTAMP '.Findings[] | select(.Id == '"$id"') | .RecordState = "ARCHIVED" | .UpdatedAt = $updated_at ' < $EXISTING_FILE
      done | jq -s '.')


    if [[ $SECURITY_HUB_PREVIOUS_FINDINGS != "[]" ]]; then
      FINDINGS_COUNT=$(echo $SECURITY_HUB_PREVIOUS_FINDINGS | jq '. | length')
      for i in $(seq 0 50 $FINDINGS_COUNT);
      do
        BATCH_FINDINGS=$(echo $SECURITY_HUB_PREVIOUS_FINDINGS | jq -c '.['"$i:$i+50"']')
        BATCH_FINDINGS_COUNT=$(echo $BATCH_FINDINGS | jq '. | length')
        if [ "$BATCH_FINDINGS_COUNT" -gt 0 ]; then
          BATCH_IMPORT_RESULT=$($AWSCLI securityhub --region "$regx" $PROFILE_OPT batch-import-findings --findings "${BATCH_FINDINGS}")
          if [[ -z "${BATCH_IMPORT_RESULT}" ]] || jq -e '.FailedCount >= 1' <<< "${BATCH_IMPORT_RESULT}" > /dev/null 2>&1; then
            echo -e "\n$RED ERROR!$NORMAL Failed to send check output to AWS Security Hub\n"
          fi
        fi
      done
    fi
  done
  rm -rf "$SH_TEMP_FOLDER"
}

sendToSecurityHub(){

  local findings="$1"
  local region="$2"

  local finding_id=$(echo ${findings} | jq -r .Id )
  SECURITYHUB_NEW_FINDINGS_IDS+=( "$finding_id" )
  BATCH_IMPORT_RESULT=$($AWSCLI securityhub --region "$region" $PROFILE_OPT batch-import-findings --findings "${findings}" 2>&1)
  # Check for success if imported
  if [[ -z "${BATCH_IMPORT_RESULT}" ]] || ! jq -e '.SuccessCount == 1' <<< "${BATCH_IMPORT_RESULT}" > /dev/null 2>&1; then
    echo "${BAD} ERROR! Failed to send check output to AWS Security Hub.${NORMAL}"
  fi

}
