Skip to main content

More Info:

Inactive roles should be cleaned up.

Risk Level

Low

Address

Security

Compliance Standards

CBP

Triage and Remediation

  • Prevention
  • Cause
  • Remediation

How to Prevent

Using Console

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

Additional Reading:

I