#!/bin/sh

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

# audit_aws_mfa
#
# Check AWS MFA
#
# Refer to Section(s) 1.2  Page(s) 12-4 CIS AWS Foundations Benchmark v1.1.0
# Refer to Section(s) 1.13 Page(s) 35-6 CIS AWS Foundations Benchmark v1.1.0
# Refer to Section(s) 1.14 Page(s) 37-8 CIS AWS Foundations Benchmark v1.1.0
#
# Refer to http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html
# Refer to http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html
# Refer to http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_physical.html#enable-hw-mfa-for-root
#.

audit_aws_mfa () {
  print_function "audit_aws_mfa"
  check_message  "MFA"
  command="aws iam get-credential-report --query 'Content' --output text | \"${base64_d}\" | cut -d, -f1,4,8 | sed '1 d' | awk -F '\\\n' '{print \$1}'"
  command_message "${command}"
  entries=$( eval "${command}" )
  for entry in ${entries}; do
    user=$( echo "${entry}" | cut -d, -f1 )
    pass=$( echo "${entry}" | cut -d, -f2 )
    mfa=$(  echo "${entry}" | cut -d, -f3 )
    if [ "${user}" = "<root_account>" ]; then
      if [ "${mfa}" = "false" ]; then
        inc_insecure "Account \"${user}\" does not have MFA enabled"
      else
        inc_secure   "Account \"${user}\" has MFA enabled"
      fi
    else
      if [ "${pass}" != "false" ]; then
        if [ "${mfa}" = "false" ]; then
          inc_insecure "Account \"${user}\" does not have MFA enabled"
        else
          inc_secure   "Account \"${user}\" has MFA enabled"
        fi
      else
        inc_secure   "Account \"${user}\" does not log into console"
      fi
    fi
  done
  command="aws iam get-account-summary | grep \"AccountMFAEnabled\" | cut -f1 -d: | sed \"s/ //g\" | sed \"s/,//g\""
  command_message "${command}"
  check=$( eval   "${command}" )
  if [ "${check}" = "1" ]; then
    inc_secure "The root account has MFA enabled"
    command="iaws iam list-virtual-mfa-devices | grep \"SerialNumber\" | grep -c \"root_account\""
    command_message "${command}"
    check=$( eval   "${command}" )
    if [ "${check}" = "0" ]; then
      inc_secure    "The root account does not have a virtual MFA"
    else
      inc_insecure  "The root account does not have a hardware MFA"
    fi
  else
    inc_insecure    "The root account does not have MFA enabled"
    inc_insecure    "The root account does not a hardware MFA"
  fi
}