> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Groups Without Users Should Be Removed

### More Info:

Empty groups should be cleaned up and should not linger around.

### Risk Level

Informational

### Address

Security

### Compliance Standards

CBP

This rule identifies IAM roles that do not require multi-factor authentication (MFA) or external ID for assumed roles. Roles without MFA or external ID can pose security risks, as they may allow unauthorized access or increase the attack surface for potential breaches. Enforcing MFA and external ID requirements adds an additional layer of security to IAM roles and helps prevent unauthorized access.

### Triage and Remediation

<Tabs>
  <Tab title="Prevention">
    ### How to Prevent

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To prevent the misconfiguration of having groups without users in AWS IAM using the AWS Management Console, follow these steps:

        1. **Regularly Review IAM Groups:**
           * Navigate to the IAM Dashboard in the AWS Management Console.
           * Click on "Groups" in the left-hand navigation pane.
           * Regularly review the list of IAM groups to identify any groups that do not have any users assigned to them.

        2. **Implement Group Usage Policies:**
           * Establish and enforce policies within your organization that require IAM groups to have at least one user or role assigned to them.
           * Ensure that any new group created has a clear purpose and assigned users or roles.

        3. **Automate Group Monitoring:**
           * Set up AWS Config rules to monitor IAM groups and detect groups without users.
           * Use the AWS Config rule "iam-group-has-users-check" to automatically check for groups without users and flag them for review.

        4. **Scheduled Audits:**
           * Schedule regular audits (e.g., monthly or quarterly) to review IAM groups and ensure compliance with your group usage policies.
           * Document the audit process and findings to maintain a record of compliance and actions taken.

        By following these steps, you can proactively prevent the misconfiguration of having groups without users in AWS IAM.
      </Accordion>

      <Accordion title="Using CLI">
        To prevent the misconfiguration of having IAM groups without users in AWS using the AWS CLI, you can follow these steps:

        1. **List All IAM Groups:**
           Use the following command to list all IAM groups in your AWS account. This will help you identify which groups exist.
           ```sh theme={null}
           aws iam list-groups
           ```

        2. **Check Group Membership:**
           For each group, check if there are any users associated with it. Replace `<group-name>` with the name of the group you want to check.
           ```sh theme={null}
           aws iam get-group --group-name <group-name>
           ```

        3. **Automate the Check:**
           Create a script to automate the process of checking each group for users. Here is a simple example in bash:
           ```sh theme={null}
           for group in $(aws iam list-groups --query 'Groups[*].GroupName' --output text); do
               users=$(aws iam get-group --group-name $group --query 'Users' --output text)
               if [ -z "$users" ]; then
                   echo "Group $group has no users."
               fi
           done
           ```

        4. **Policy to Prevent Empty Groups:**
           Implement a policy or governance rule within your organization to ensure that IAM groups are regularly audited and empty groups are either populated with users or removed. This can be enforced through periodic reviews and automated scripts.

        By following these steps, you can prevent the misconfiguration of having IAM groups without users in AWS using the AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To prevent the creation of IAM groups without users in AWS, Azure, and GCP using Python scripts, you can follow these steps:

        ### AWS (Amazon Web Services)

        1. **Install Boto3 Library**:
           Ensure you have the Boto3 library installed to interact with AWS services.
           ```bash theme={null}
           pip install boto3
           ```

        2. **Create a Python Script to Check and Prevent Empty Groups**:
           ```python theme={null}
           import boto3

           iam = boto3.client('iam')

           def prevent_empty_groups():
               groups = iam.list_groups()['Groups']
               for group in groups:
                   group_name = group['GroupName']
                   users = iam.get_group(GroupName=group_name)['Users']
                   if not users:
                       print(f"Group {group_name} is empty. Please add users or remove the group.")
                       # Optionally, you can delete the group here
                       # iam.delete_group(GroupName=group_name)

           prevent_empty_groups()
           ```

        ### Azure (Microsoft Azure)

        1. **Install Azure Identity and Management Libraries**:
           Ensure you have the Azure Identity and Management libraries installed.
           ```bash theme={null}
           pip install azure-identity azure-mgmt-authorization
           ```

        2. **Create a Python Script to Check and Prevent Empty Groups**:
           ```python theme={null}
           from azure.identity import DefaultAzureCredential
           from azure.mgmt.authorization import AuthorizationManagementClient

           credential = DefaultAzureCredential()
           subscription_id = 'your-subscription-id'
           client = AuthorizationManagementClient(credential, subscription_id)

           def prevent_empty_groups():
               groups = client.groups.list()
               for group in groups:
                   group_id = group.id
                   members = client.group_members.list(group_id)
                   if not list(members):
                       print(f"Group {group.display_name} is empty. Please add users or remove the group.")
                       # Optionally, you can delete the group here
                       # client.groups.delete(group_id)

           prevent_empty_groups()
           ```

        ### GCP (Google Cloud Platform)

        1. **Install Google Cloud IAM Library**:
           Ensure you have the Google Cloud IAM library installed.
           ```bash theme={null}
           pip install google-cloud-iam
           ```

        2. **Create a Python Script to Check and Prevent Empty Groups**:
           ```python theme={null}
           from google.cloud import iam_v1

           client = iam_v1.IAMClient()

           def prevent_empty_groups():
               groups = client.list_groups()
               for group in groups:
                   group_name = group.name
                   members = client.list_group_members(group_name)
                   if not list(members):
                       print(f"Group {group.display_name} is empty. Please add users or remove the group.")
                       # Optionally, you can delete the group here
                       # client.delete_group(group_name)

           prevent_empty_groups()
           ```

        ### Summary

        1. **Install the necessary libraries** for AWS, Azure, and GCP.
        2. **Create a Python script** to list all IAM groups.
        3. **Check if each group has users**.
        4. **Print a warning message** if a group is empty, and optionally delete the group.

        These scripts will help you prevent the creation of empty IAM groups by checking for users and alerting you if any group is found to be empty.
      </Accordion>
    </AccordionGroup>
  </Tab>

  <Tab title="Cause">
    ### Check Cause

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        1. Log in to the AWS Management Console and navigate to the IAM dashboard.
        2. In the IAM dashboard, click on "Groups" in the left navigation pane. This will display a list of all the IAM groups in your AWS account.
        3. Click on each group to view its details. In the "Users" tab, you can see the list of users associated with that group.
        4. If the "Users" tab is empty, it means that the group does not have any users associated with it and should be removed.
      </Accordion>

      <Accordion title="Using CLI">
        1. First, you need to install and configure AWS CLI on your local machine. You can do this by following the instructions provided by AWS. Make sure you have the necessary permissions to execute IAM related commands.

        2. Once the AWS CLI is set up, you can list all the IAM groups in your AWS account by running the following command:
           ```
           aws iam list-groups
           ```
           This command will return a JSON object that contains information about all the IAM groups in your AWS account.

        3. To list all the users in a specific IAM group, you can use the following command:
           ```
           aws iam get-group --group-name GroupName
           ```
           Replace 'GroupName' with the name of the IAM group you want to check. This command will return a JSON object that contains information about the IAM group, including a list of its users.

        4. If the 'Users' array in the returned JSON object is empty, it means that the IAM group has no users. You can use a Python script to automate this check for all IAM groups. Here is a simple example:
           ```python theme={null}
           import json
           import subprocess

           # Get the list of all IAM groups
           groups = json.loads(subprocess.getoutput('aws iam list-groups'))

           for group in groups['Groups']:
               # Get the details of the group
               group_details = json.loads(subprocess.getoutput(f'aws iam get-group --group-name {group["GroupName"]}'))

               # Check if the group has no users
               if not group_details['Users']:
                   print(f'The group {group["GroupName"]} has no users.')
           ```
           This script will print the names of all IAM groups that have no users.
      </Accordion>

      <Accordion title="Using Python">
        1. Install the necessary Python libraries: Before you start, you need to install the AWS SDK for Python (Boto3) which allows Python developer to write software that makes use of services like Amazon S3, Amazon EC2, etc.

        ```python theme={null}
        pip install boto3
        ```

        2. Set up AWS credentials: You need to configure your AWS credentials. You can do this by creating the files \~/.aws/credentials. At the very least, the credentials file should specify the access key and secret access key. To specify these for the default profile, you can use the following format:

        ```python theme={null}
        [default]
        aws_access_key_id = YOUR_ACCESS_KEY
        aws_secret_access_key = YOUR_SECRET_KEY
        ```

        3. Write a Python script to list all IAM groups and check if they have any users:

        ```python theme={null}
        import boto3

        # Create IAM client
        iam = boto3.client('iam')

        # List groups
        response = iam.list_groups()

        # For each group
        for group in response['Groups']:
            # Get the group name
            group_name = group['GroupName']

            # List users in the group
            users_response = iam.get_group(GroupName=group_name)

            # If the group has no users
            if not users_response['Users']:
                print(f'Group {group_name} has no users.')
        ```

        4. Run the Python script: You can run the Python script using any Python environment. If the script prints out any group names, those groups have no users and should be removed. If the script doesn't print out anything, then all groups have at least one user.
      </Accordion>
    </AccordionGroup>
  </Tab>

  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the "Groups Without Users Should Be Removed" misconfiguration in AWS using AWS console, you can follow these steps:

        1. Open the AWS Management Console and navigate to the Identity and Access Management (IAM) service.

        2. In the left navigation pane, click on "Groups".

        3. Identify any groups that do not have any users assigned to them.

        4. Select the group(s) that do not have any users assigned to them.

        5. Click on the "Group Actions" dropdown menu and select "Delete Group".

        6. Confirm the group deletion by clicking "Yes, Delete" in the pop-up window.

        7. Repeat steps 3-6 for any other groups without users.

        By following these steps, you will have successfully remediated the "Groups Without Users Should Be Removed" misconfiguration in AWS using the AWS console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Groups Without Users Should Be Removed" in AWS using AWS CLI, follow the below steps:

        1. Open the AWS CLI and run the following command to list all the groups in your AWS account:
           ```
           aws iam list-groups
           ```

        2. Identify the groups that do not have any users associated with them.

        3. Run the following command to delete the group:
           ```
           aws iam delete-group --group-name <group-name>
           ```
           Replace `<group-name>` with the name of the group that you want to delete.

        4. Repeat steps 2 and 3 for all the groups that do not have any users associated with them.

        5. Verify that all the groups without users have been deleted by running the following command:
           ```
           aws iam list-groups
           ```
           This should return a list of groups that have at least one user associated with them.

        By following the above steps, you can remediate the misconfiguration "Groups Without Users Should Be Removed" in AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Groups Without Users Should Be Removed" in AWS using Python, follow these steps:

        1. Install the AWS SDK for Python (boto3) using pip:

        ```
        pip install boto3
        ```

        2. Create an AWS IAM client using boto3:

        ```python theme={null}
        import boto3

        iam = boto3.client('iam')
        ```

        3. Use the `list_groups` method to get a list of all IAM groups:

        ```python theme={null}
        response = iam.list_groups()
        groups = response['Groups']
        ```

        4. Use a loop to iterate over the list of groups and check if each group has any users:

        ```python theme={null}
        for group in groups:
            group_name = group['GroupName']
            response = iam.get_group(GroupName=group_name)
            users = response['Users']
            if not users:
                iam.delete_group(GroupName=group_name)
        ```

        5. Use the `delete_group` method to delete any groups that do not have any users.

        6. Save the Python script and run it to remediate the misconfiguration.

        Note: Before running the script, make sure you have the necessary permissions to delete IAM groups.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_groups\_manage\_add-remove-users.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_add-remove-users.html)
