#!/usr/bin/env bash

# Prowler - the handy cloud security tool (c) by Toni de la Fuente
#
# This Prowler check is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
#
# You should have received a copy of the license along with this
# work. If not, see <http://creativecommons.org/licenses/by-nc-sa/4.0/>.

CHECK_ID_check116="1.16"
CHECK_TITLE_check116="[check116] Ensure IAM policies are attached only to groups or roles (Scored)"
CHECK_SCORED_check116="SCORED"
CHECK_TYPE_check116="LEVEL1"
CHECK_ALTERNATE_check116="check116"

check116(){
  # "Ensure IAM policies are attached only to groups or roles (Scored)"
  LIST_USERS=$($AWSCLI iam list-users --query 'Users[*].UserName' --output text $PROFILE_OPT --region $REGION)
  C116_NUM_USERS=0
  for user in $LIST_USERS;do
    USER_POLICY=$($AWSCLI iam list-attached-user-policies --output text $PROFILE_OPT --region $REGION --user-name $user)
    if [[ $USER_POLICY ]]; then
      textFail "$user has managed policy directly attached "
      C116_NUM_USERS=$(expr $C116_NUM_USERS + 1)
    fi
    USER_POLICY=$($AWSCLI iam list-user-policies --output text $PROFILE_OPT --region $REGION --user-name $user)
    if [[ $USER_POLICY ]]; then
      textFail "$user has inline policy directly attached "
      C116_NUM_USERS=$(expr $C116_NUM_USERS + 1)
    fi
  done
  if [[ $C116_NUM_USERS -eq 0 ]]; then
    textPass "No policies attached to users."
  fi
}
