#!/bin/sh

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

# audit_aws_cf
#
# Check AWS CloudFormation
#
# Refer to https://www.cloudconformity.com/conformity-rules/CloudFormation/cloudformation-stack-notification.html
# Refer to https://www.cloudconformity.com/conformity-rules/CloudFormation/cloudformation-stack-policy.html
#.

audit_aws_cf () {
  # Check Cloud Formation stacks are using SNS
  print_function  "audit_aws_cf"
  check_message   "CloudFormation"
  command="aws cloudformation list-stacks --region \"${aws_region}\" --query 'StackSummaries[].StackId' --output text"
  command_message "${command}"
  stacks=$( eval  "${command}" )
  for stack in ${stacks}; do 
    command="aws cloudformation describe-stacks --region \"${aws_region}\" --stack-name \"${stack}\" --query 'Stack[].NotificationARNs' --output text"
    command_message "${command}"
    check=$( eval   "${command}" )
    stack=$( echo   "${stack}" | cut -f2 -d/ )
    if [ "${check}" ]; then
      inc_secure    "SNS topic ${exists} for CloudFormation stack \"${stack}\""
    else
      inc_insecure  "SNS topic does not exist for CloudFormation stack \"${stack}\""
    fi
  done
  # Check stacks have a policy
  command="aws cloudformation list-stacks --region \"${aws_region}\" --query 'StackSummaries[].StackName' --output text"
  command_message "${command}"
  stacks=$( eval  "${command}" )
  for stack in ${stacks}; do 
    command="aws cloudformation get-stack-policy --region \"${aws_region}\" --stack-name \"${stack}\" --query 'StackPolicyBody' --output text 2> /dev/null"
    command_message "${command}"
    check=$( eval   "${command}" )
    if [ "${check}" ]; then
      inc_secure    "CloudFormation stack \"${stack}\" has a policy"
    else
      inc_insecure  "CloudFormation stack \"${stack}\" does not have a policy"
    fi
  done
}

