> ## 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.

# Inactive Roles Should Be Removed

### More Info:

Inactive roles should be cleaned up.

### Risk Level

Low

### Address

Security

### Compliance Standards

CBP

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To prevent inactive roles in IAM using the AWS Management Console, follow these steps:

        1. **Regularly Review IAM Roles:**
           * Navigate to the IAM dashboard in the AWS Management Console.
           * Click on "Roles" to view the list of all IAM roles.
           * Regularly review the list of roles to identify any that have not been used for a significant period.

        2. **Enable CloudTrail Logging:**
           * Go to the CloudTrail service in the AWS Management Console.
           * Ensure that CloudTrail is enabled to log all API activity.
           * Use CloudTrail logs to monitor the usage of IAM roles and identify inactive ones.

        3. **Set Up Automated Alerts:**
           * Use AWS Config to create a rule that checks for IAM roles that have not been used within a specified period.
           * Set up Amazon SNS (Simple Notification Service) to send alerts when the rule is triggered, indicating an inactive role.

        4. **Implement Lifecycle Policies:**
           * Establish and document a policy for the lifecycle of IAM roles within your organization.
           * Ensure that roles are reviewed periodically (e.g., quarterly) and that any roles identified as inactive are flagged for removal according to the policy.

        By following these steps, you can proactively manage and prevent the accumulation of inactive IAM roles in your AWS environment.
      </Accordion>

      <Accordion title="Using CLI">
        To prevent inactive roles in IAM using AWS CLI, you can follow these steps:

        1. **List All IAM Roles:**
           Use the following command to list all IAM roles in your AWS account. This will help you identify roles that are potentially inactive.
           ```sh theme={null}
           aws iam list-roles
           ```

        2. **Get Role Last Used Information:**
           For each role, retrieve the last used information to determine if the role has been inactive for a certain period. Replace `ROLE_NAME` with the actual role name.
           ```sh theme={null}
           aws iam get-role --role-name ROLE_NAME
           ```

        3. **Automate Inactivity Check:**
           Create a script to automate the process of checking the last used date for each role. If a role has not been used for a specified period (e.g., 90 days), mark it for review or deletion. Here is a basic example in Python:
           ```python theme={null}
           import boto3
           from datetime import datetime, timedelta

           iam = boto3.client('iam')
           roles = iam.list_roles()['Roles']

           for role in roles:
               role_name = role['RoleName']
               role_details = iam.get_role(RoleName=role_name)
               last_used = role_details['Role']['RoleLastUsed']
               
               if 'LastUsedDate' in last_used:
                   last_used_date = last_used['LastUsedDate']
                   if datetime.now() - last_used_date > timedelta(days=90):
                       print(f"Role {role_name} has been inactive for more than 90 days.")
               else:
                   print(f"Role {role_name} has never been used.")
           ```

        4. **Implement Role Deletion Policy:**
           Establish a policy for deleting or deactivating roles that have been inactive for a specified period. Use the following command to delete an inactive role. Replace `ROLE_NAME` with the actual role name.
           ```sh theme={null}
           aws iam delete-role --role-name ROLE_NAME
           ```

        By following these steps, you can effectively monitor and manage inactive IAM roles in AWS using the AWS CLI and Python scripting.
      </Accordion>

      <Accordion title="Using Python">
        To prevent inactive roles in IAM using Python scripts, you can follow these steps:

        1. **Set Up AWS SDK (Boto3) for Python**:
           * Ensure you have the AWS SDK for Python (Boto3) installed. You can install it using pip if you haven't already:
             ```bash theme={null}
             pip install boto3
             ```

        2. **Identify Inactive Roles**:
           * Write a Python script to identify roles that have not been used for a specified period. You can use the `get_role` and `list_roles` methods from Boto3 to fetch role details and their last used information.

        3. **Automate Role Monitoring**:
           * Create a script that runs periodically (e.g., using a cron job or AWS Lambda) to check for inactive roles and log or notify about them.

        4. **Implement Preventive Measures**:
           * Use the script to enforce policies or alerts that notify administrators about inactive roles, so they can take action to remove or review them.

        Here is a sample Python script to identify and log inactive roles:

        ```python theme={null}
        import boto3
        from datetime import datetime, timedelta

        # Initialize a session using Amazon IAM
        session = boto3.Session(profile_name='your_profile_name')
        iam_client = session.client('iam')

        # Define the inactivity period (e.g., 90 days)
        inactivity_period = 90
        threshold_date = datetime.utcnow() - timedelta(days=inactivity_period)

        def get_inactive_roles():
            inactive_roles = []
            paginator = iam_client.get_paginator('list_roles')
            for page in paginator.paginate():
                for role in page['Roles']:
                    role_name = role['RoleName']
                    role_details = iam_client.get_role(RoleName=role_name)
                    last_used = role_details['Role']['RoleLastUsed']
                    if 'LastUsedDate' in last_used:
                        last_used_date = last_used['LastUsedDate']
                        if last_used_date < threshold_date:
                            inactive_roles.append(role_name)
                    else:
                        # If the role has never been used, consider it inactive
                        inactive_roles.append(role_name)
            return inactive_roles

        def main():
            inactive_roles = get_inactive_roles()
            if inactive_roles:
                print("Inactive roles detected:")
                for role in inactive_roles:
                    print(f" - {role}")
            else:
                print("No inactive roles detected.")

        if __name__ == "__main__":
            main()
        ```

        ### Key Points:

        1. **Set Up AWS SDK (Boto3)**:
           * Ensure Boto3 is installed and configured with the necessary AWS credentials.

        2. **Identify Inactive Roles**:
           * Use the `list_roles` and `get_role` methods to fetch role details and their last used information.

        3. **Automate Role Monitoring**:
           * Schedule the script to run periodically to monitor inactive roles.

        4. **Implement Preventive Measures**:
           * Log or notify administrators about inactive roles for further action.

        This script helps in identifying inactive roles, which can then be reviewed and removed manually or through additional automation if necessary.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

        2. In the navigation pane, choose "Roles". This will display a list of all the IAM roles that are currently configured within your AWS environment.

        3. Select a role to inspect. In the "Last activity" column, you can see when the role was last used to make an AWS request. If the "Last activity" shows "None", it means the role has not been used to make a request.

        4. Repeat this process for all roles in the list. Any role that has not been used recently (based on your organization's policy, e.g., 90 days) can be considered as inactive and should be reviewed for potential removal.
      </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. Once you have AWS CLI installed and configured, you can proceed to the next steps.

        2. Use the following command to list all the IAM roles in your AWS account:

           ```
           aws iam list-roles
           ```

           This command will return a JSON object that contains information about all the IAM roles in your AWS account.

        3. To check the last activity of each role, you can use the following command:

           ```
           aws iam get-role --role-name {role-name}
           ```

           Replace `{role-name}` with the name of the role you want to check. This command will return a JSON object that contains information about the specified role, including the `RoleLastUsed` field which indicates the last time the role was used.

        4. Repeat step 3 for each role listed in step 2. If the `RoleLastUsed` field is not present or the date is older than your company's policy (for example, 90 days), the role is considered inactive.
      </Accordion>

      <Accordion title="Using Python">
        1. Install the necessary Python libraries: Before you start, you need to install the AWS SDK for Python (Boto3) to interact with AWS services. You can install it using pip:

           ```
           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 and \~/.aws/config:

           \~/.aws/credentials:

           ```
           [default]
           aws_access_key_id = YOUR_ACCESS_KEY
           aws_secret_access_key = YOUR_SECRET_KEY
           ```

           \~/.aws/config:

           ```
           [default]
           region=us-east-1
           ```

        3. Write a Python script to detect inactive IAM roles: The following script lists all IAM roles and checks if they have been used in the last 90 days. If not, it prints them out:

           ```python theme={null}
           import boto3
           from datetime import datetime, timedelta

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

           # Get the current date
           current_date = datetime.now()

           # Get all IAM roles
           roles = iam.list_roles()['Roles']

           # Check each role
           for role in roles:
               # Get the role name
               role_name = role['RoleName']

               # Get the last used date of the role
               last_used_date = role.get('RoleLastUsed', {}).get('LastUsedDate')

               # If the role has never been used, print it out
               if last_used_date is None:
                   print(f"The role {role_name} has never been used.")
                   continue

               # If the role has not been used in the last 90 days, print it out
               if last_used_date < current_date - timedelta(days=90):
                   print(f"The role {role_name} has not been used in the last 90 days.")
           ```

        4. Run the Python script: You can run the script using the Python interpreter. The script will print out all IAM roles that have not been used in the last 90 days:

           ```
           python detect_inactive_roles.py
           ```

        This script only detects inactive IAM roles. To remove them, you would need to add additional code to delete the roles or manually remove them through the AWS Management Console.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Sure, here are the step by step instructions to remediate the "Inactive Roles Should Be Removed" misconfiguration in AWS:

        1. Login to your AWS console.
        2. Navigate to the "Identity and Access Management (IAM)" service.
        3. Click on "Roles" from the left-hand menu.
        4. Review the list of roles and identify any inactive roles.
        5. Select the inactive role by clicking on the role name.
        6. Click on the "Delete Role" button.
        7. Confirm the deletion by clicking on "Yes, delete" button.

        Note: Before deleting any role, make sure that the role is not being used by any resources or services in your AWS account. If a role is being used, then removing it can cause disruption to the resources or services.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Inactive Roles Should Be Removed" for AWS using AWS CLI, follow these steps:

        1. Open the AWS CLI on your computer.

        2. Run the following command to list all the roles in your AWS account:

        ```
        aws iam list-roles
        ```

        3. Identify the inactive roles that have not been used for a long time. You can check the "LastUsedDate" attribute of each role to determine when it was last used.

        4. Run the following command to delete the inactive roles:

        ```
        aws iam delete-role --role-name <role-name>
        ```

        Replace `<role-name>` with the name of the inactive role that you want to delete.

        5. Repeat steps 3-4 for all the inactive roles that you want to remove.

        Note: Before deleting any role, make sure that it is not being used by any resources or applications in your AWS account. Deleting a role that is still in use can cause issues with your applications and services.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of inactive roles in AWS, you can use the following steps using Python:

        1. First, you need to list all the roles in your AWS account using the `boto3` library in Python. You can use the following code to achieve this:

        ```python theme={null}
        import boto3

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

        # List roles
        response = iam.list_roles()
        roles = response['Roles']
        ```

        2. Once you have the list of roles, you need to check if any of the roles are inactive. You can do this by checking the `CreateDate` attribute of the role. If the role was created more than a certain number of days ago (e.g. 90 days), you can consider it inactive. You can use the following code to achieve this:

        ```python theme={null}
        import datetime

        # Define the number of days after which a role is considered inactive
        inactive_days = 90

        # Check if any roles are inactive
        for role in roles:
            create_date = role['CreateDate'].replace(tzinfo=None)
            if (datetime.datetime.now() - create_date).days > inactive_days:
                print(f"Role {role['RoleName']} is inactive and should be removed.")
        ```

        3. Finally, to remove the inactive roles, you can use the `delete_role` method of the `boto3` library. You can use the following code to achieve this:

        ```python theme={null}
        # Delete inactive roles
        for role in roles:
            create_date = role['CreateDate'].replace(tzinfo=None)
            if (datetime.datetime.now() - create_date).days > inactive_days:
                iam.delete_role(RoleName=role['RoleName'])
                print(f"Role {role['RoleName']} has been deleted.")
        ```

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

### Additional Reading:

* [https://aws.amazon.com/blogs/security/identify-unused-iam-roles-remove-confidently-last-used-timestamp](https://aws.amazon.com/blogs/security/identify-unused-iam-roles-remove-confidently-last-used-timestamp)
