#!/bin/sh

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

# audit_aws_sns
#
# Check AWS SNS
# 
# Refer to Section(s) 3.15 Page(s) 129-30 CIS AWS Foundations Benchmark v1.1.0
#
# Refer to https://www.cloudconformity.com/conformity-rules/SNS/sns-topic-exposed.html
#.

audit_aws_sns () {
  print_function  "audit_aws_sns"
  check_message   "SNS"
  command="aws sns list-topics --region \"${aws_region}\" --query 'Topics[].TopicArn' --output text"
  command_message    "${command}"
  topic_list=$( eval "${command}" )
  for topic in ${topic_list}; do
    # Check SNS topics have subscribers
    command="aws sns list-subscriptions-by-topic --region \"${aws_region}\" --topic-arn \"${topic}\" --output text"
    command_message     "${command}"
    subscribers=$( eval "${command}" )
    if [ -z "${subscribers}" ]; then
      inc_insecure "SNS topic \"${topic}\" has no subscribers"
    else
      inc_secure   "SNS topic has subscribers, review subscribers"
    fi
    #check SNS topics are not publicly accessible
    command="aws sns get-topic-attributes --region \"${aws_region}\" --topic-arn \"${topic}\" --query 'Attributes.Policy'  |grep -E \"\*|{\\\"AWS\\\":\\\"\*\\\"}\""
    command_message   "${command}"
    sns_check=$( eval "${command}" )
    if [ -n "${sns_check}" ]; then
      inc_insecure "SNS topic \"${topic}\" is publicly accessible"
    else
      inc_secure   "SNS topic is not publicly accessible"
    fi
  done
}

