#!/bin/sh

# shellcheck disable=SC1090
# shellcheck disable=SC2034
# shellcheck disable=SC2154

# audit_azure_key_vault_logging
#
# Check Azure Key Vault Logging
#
# 6.1.1.4  Ensure that logging for Azure Key Vault is 'Enabled'
#
# Refer to Section(s) 6.1.1.4 Page(s) 207-10 CIS Microsoft Azure Foundations Benchmark v5.0.0
#
# This requires the Azure CLI to be installed and configured
#.

audit_azure_key_vault_logging () {
  print_function "audit_azure_key_vault_logging"
  check_message  "Azure Key Vault Logging"
  command="az keyvault list --query \"[].id\" --output tsv 2>/dev/null"
  command_message   "${command}"
  vault_ids=$( eval "${command}" 2> /dev/null )
  if [ -z "${vault_ids}" ]; then
    info_message "No Key Vaults found"
    return
  fi
  for vault_id in ${vault_ids}; do
    command="az monitor diagnostic-settings list --resource \"${vault_id}\" --query \"[].name\" --output tsv 2>/dev/null"
    command_message   "${command}"
    res_names=$( eval "${command}" )
    for res_name in ${res_names}; do
      command="az monitor diagnostic-settings show --resource \"${vault_id}\" --name \"${res_name}\" --query \"logs\" --output tsv 2>/dev/null"
      command_message "${command}"
      az monitor diagnostic-settings show --resource "${vault_id}" --name "${res_name}" --query "logs" --output tsv 2>/dev/null |
      while read -r line; do
        category=$( echo "${line}" | awk '{print $1}' )
        enabled=$(  echo "${line}" | awk '{print $2}' )
        if [ "${enabled}" = "True" ]; then
          inc_secure   "Key Vault \"${res_name}\" logging enabled for \"${category}\""
        else
          inc_insecure "Key Vault \"${res_name}\" logging disabled for \"${category}\""
        fi
      done
    done
  done
}
