#!/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_extra7147="7.147"
CHECK_TITLE_extra7147="[extra7147] Check if S3 Glacier vaults have policies which allow access to everyone"
CHECK_SCORED_extra7147="NOT_SCORED"
CHECK_CIS_LEVEL_extra7147="EXTRA"
CHECK_SEVERITY_extra7147="Critical"
CHECK_ASFF_RESOURCE_TYPE_extra7147="AwsGlacierVault"
CHECK_ALTERNATE_check7147="extra7147"
CHECK_SERVICENAME_extra7147="glacier"
CHECK_RISK_extra7147='Vaults accessible to everyone could expose sensitive data to bad actors'
CHECK_REMEDIATION_extra7147='Ensure vault policy does not have principle as *'
CHECK_DOC_extra7147='https://docs.aws.amazon.com/amazonglacier/latest/dev/access-control-overview.html'
CHECK_CAF_EPIC_extra7147='Data Protection'

extra7147(){
  for regx in $REGIONS; do
  LIST_OF_VAULTS=$($AWSCLI glacier list-vaults $PROFILE_OPT --region $regx --account-id $ACCOUNT_NUM --query VaultList[*].VaultName --output text 2>&1|xargs -n1)
  if [[ $(echo "$LIST_OF_VAULTS" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
      textInfo "$regx: Access Denied trying to list vaults" "$regx"
      continue
  fi
  if [[ $LIST_OF_VAULTS ]]; then
    for vault in $LIST_OF_VAULTS;do
      VAULT_POLICY_STATEMENTS=$($AWSCLI glacier $PROFILE_OPT get-vault-access-policy --region $regx --account-id $ACCOUNT_NUM --vault-name $vault --output json --query policy.Policy 2>&1)
      if [[ $VAULT_POLICY_STATEMENTS == *GetVaultAccessPolicy* ]]; then
        textInfo "$regx: Vault $vault doesn't have any policy" "$regx" "$vault"
      else
        VAULT_POLICY_BAD_STATEMENTS=$(echo $VAULT_POLICY_STATEMENTS | jq '. | fromjson' | jq '.Statement[] | select(.Effect=="Allow") | select(.Principal=="*" or .Principal.AWS=="*" or .Principal.CanonicalUser=="*")')
        if [[ $VAULT_POLICY_BAD_STATEMENTS != "" ]]; then
          textFail "$regx: Vault $vault has policy which allows access to everyone" "$regx" "$vault"
        else
          textPass "$regx: Vault $vault has policy which does not allow access to everyone" "$regx" "$vault"
        fi
      fi
    done
  else
    textInfo "$regx: No Glacier vaults found" "$regx"
  fi
 done
}