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

# User Account Without Any Usage Should Be Removed

### More Info:

Any unused IAM user without console access and API access should be removed as an extra security measure for protecting your AWS resources against unapproved access.

### Risk Level

Medium

### Address

Security

### Compliance Standards

CISAWS, CBP, HIPAA, SOC2, ISO27001, HITRUST, NISTCSF, PCIDSS

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To prevent user accounts without any usage in AWS IAM using the AWS Management Console, follow these steps:

        1. **Monitor User Activity:**
           * Navigate to the IAM Dashboard in the AWS Management Console.
           * Go to the "Access Advisor" tab for each user to review their last accessed services and activities.
           * Regularly check the "Last Activity" column to identify users who have not accessed any services for a specified period.

        2. **Set Up CloudWatch Alarms:**
           * Create CloudWatch Alarms to monitor IAM user activity.
           * Set up alarms to trigger notifications when there is no activity for a specified period.
           * Use these alarms to identify inactive users promptly.

        3. **Enable Logging with CloudTrail:**
           * Ensure AWS CloudTrail is enabled to log all IAM user activities.
           * Regularly review CloudTrail logs to identify users with no activity.
           * Use CloudTrail insights to detect unusual inactivity patterns.

        4. **Implement IAM Policies:**
           * Create and attach IAM policies that enforce regular reviews of user activity.
           * Use policies to mandate the removal or deactivation of users who have not logged in or performed any actions within a specified timeframe.
           * Ensure compliance with these policies through regular audits and reviews.

        By following these steps, you can effectively monitor and manage IAM user accounts to ensure that inactive accounts are identified and addressed promptly.
      </Accordion>

      <Accordion title="Using CLI">
        To prevent user accounts without any usage in AWS IAM using the AWS CLI, you can follow these steps:

        1. **List All IAM Users:**
           Use the following command to list all IAM users in your AWS account. This will help you identify which users exist and need to be monitored for activity.

           ```sh theme={null}
           aws iam list-users
           ```

        2. **Monitor User Activity:**
           Regularly check the last activity of each IAM user. You can use the following command to get the last used information for each user. This will help you identify users who have not used their credentials recently.

           ```sh theme={null}
           aws iam get-user --user-name <username>
           ```

        3. **Automate Inactive User Detection:**
           Create a script to automate the detection of inactive users. You can use AWS CLI commands within a Python script to check the last activity of each user and flag those who have not been active for a specified period.

           Example Python script snippet:

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

           iam = boto3.client('iam')
           users = iam.list_users()['Users']

           for user in users:
               username = user['UserName']
               last_used = iam.get_user(UserName=username)['User'].get('PasswordLastUsed', None)
               if last_used:
                   last_used_date = last_used.replace(tzinfo=None)
                   if datetime.now() - last_used_date > timedelta(days=90):  # Example: 90 days of inactivity
                       print(f"User {username} has been inactive for more than 90 days.")
           ```

        4. **Implement a Policy for Regular Review:**
           Establish a policy to regularly review IAM users and their activity. This can be done by scheduling the above script to run periodically (e.g., using AWS Lambda and CloudWatch Events) to ensure continuous monitoring and prompt action on inactive users.

           Example of scheduling a Lambda function using AWS CLI:

           ```sh theme={null}
           aws events put-rule --schedule-expression "rate(7 days)" --name "InactiveUserCheck"
           aws lambda add-permission --function-name <lambda-function-name> --statement-id <unique-id> --action 'lambda:InvokeFunction' --principal events.amazonaws.com --source-arn <rule-arn>
           aws events put-targets --rule "InactiveUserCheck" --targets "Id"="<target-id>","Arn"="<lambda-function-arn>"
           ```

        By following these steps, you can effectively prevent user accounts without any usage from remaining in your AWS IAM, ensuring better security and management of your cloud resources.
      </Accordion>

      <Accordion title="Using Python">
        To prevent user accounts without any usage in IAM from existing in AWS, Azure, and GCP using Python scripts, you can follow these steps:

        ### AWS (Amazon Web Services)

        1. **List All IAM Users:**
           Use the `boto3` library to list all IAM users.

           ```python theme={null}
           import boto3

           iam_client = boto3.client('iam')

           def list_iam_users():
               response = iam_client.list_users()
               return response['Users']

           users = list_iam_users()
           ```

        2. **Check User Activity:**
           Check the last activity of each user by examining their access keys and login profile.

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

           def get_user_last_activity(user_name):
               access_keys = iam_client.list_access_keys(UserName=user_name)['AccessKeyMetadata']
               last_used = None
               for key in access_keys:
                   key_last_used = iam_client.get_access_key_last_used(AccessKeyId=key['AccessKeyId'])['AccessKeyLastUsed']
                   if 'LastUsedDate' in key_last_used:
                       if not last_used or key_last_used['LastUsedDate'] > last_used:
                           last_used = key_last_used['LastUsedDate']
               return last_used

           for user in users:
               last_activity = get_user_last_activity(user['UserName'])
               if last_activity and last_activity < datetime.now() - timedelta(days=90):
                   print(f"User {user['UserName']} has not been active for 90 days.")
           ```

        ### Azure (Microsoft Azure)

        1. **List All Users:**
           Use the `azure-identity` and `azure-graphrbac` libraries to list all users.

           ```python theme={null}
           from azure.identity import DefaultAzureCredential
           from azure.graphrbac import GraphRbacManagementClient

           credential = DefaultAzureCredential()
           client = GraphRbacManagementClient(credential, 'YOUR_TENANT_ID')

           def list_users():
               users = client.users.list()
               return list(users)

           users = list_users()
           ```

        2. **Check User Activity:**
           Check the last sign-in activity of each user.

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

           def get_user_last_sign_in(user):
               # Assuming you have a way to get the last sign-in date
               # This might require additional API calls or logs
               last_sign_in = user.sign_in_activity.last_sign_in_date_time
               return last_sign_in

           for user in users:
               last_sign_in = get_user_last_sign_in(user)
               if last_sign_in and last_sign_in < datetime.now() - timedelta(days=90):
                   print(f"User {user.user_principal_name} has not signed in for 90 days.")
           ```

        ### GCP (Google Cloud Platform)

        1. **List All Users:**
           Use the `google-auth` and `google-api-python-client` libraries to list all users.

           ```python theme={null}
           from google.oauth2 import service_account
           from googleapiclient.discovery import build

           credentials = service_account.Credentials.from_service_account_file('path/to/your/service-account-file.json')
           service = build('admin', 'directory_v1', credentials=credentials)

           def list_users():
               results = service.users().list(customer='my_customer', maxResults=200, orderBy='email').execute()
               return results.get('users', [])

           users = list_users()
           ```

        2. **Check User Activity:**
           Check the last login time of each user.

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

           def get_user_last_login(user):
               last_login = user.get('lastLoginTime')
               if last_login:
                   return datetime.strptime(last_login, '%Y-%m-%dT%H:%M:%S.%fZ')
               return None

           for user in users:
               last_login = get_user_last_login(user)
               if last_login and last_login < datetime.now() - timedelta(days=90):
                   print(f"User {user['primaryEmail']} has not logged in for 90 days.")
           ```

        These scripts will help you identify users who have not been active for a specified period (e.g., 90 days). You can then take appropriate actions, such as notifying administrators or automatically deactivating these accounts.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        1. Log 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 "Users". This will display a list of all IAM users that are currently set up for your AWS account.

        3. For each user, click on the user name to open the user's "Summary" page. Here, you can see the "Access Advisor" tab which shows the service permissions granted to the user and when those services were last accessed.

        4. If the "Last accessed" column shows "No activity", it means the user account has not been used to make an AWS request. If the user account has not been used for a long period of time, it may be a misconfiguration and should be reviewed.
      </Accordion>

      <Accordion title="Using CLI">
        1. Install and configure AWS CLI: Before you can start using AWS CLI, you need to install it on your local machine and configure it with your AWS account credentials. You can do this by running the following commands:

           Installation: `pip install awscli`

           Configuration: `aws configure`

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

           `aws iam list-users`

        3. Check the last activity of each user: For each user, you can check their last activity date by using the following command:

           `aws iam get-user --user-name <username>`

           Replace `<username>` with the name of the user. This command will return a JSON object that includes the `PasswordLastUsed` field, which indicates the last time the user logged in to the AWS Management Console.

        4. Analyze the output: If the `PasswordLastUsed` field is not present or the date is too old, it means the user account has not been used for a long time and should be considered for removal.
      </Accordion>

      <Accordion title="Using Python">
        1. **Import necessary libraries and establish a connection with AWS:**
           You need to import the boto3 library, which is the Amazon Web Services (AWS) SDK for Python. It allows Python developers to write software that makes use of services like Amazon S3, Amazon EC2, etc. You also need to establish a connection with AWS using your access keys.

           ```python theme={null}
           import boto3
           import datetime
           from dateutil.tz import tzutc

           # Create IAM client
           iam = boto3.client(
               'iam',
               aws_access_key_id='YOUR_ACCESS_KEY',
               aws_secret_access_key='YOUR_SECRET_KEY',
               aws_session_token='SESSION_TOKEN',
           )
           ```

        2. **Fetch all the IAM users:**
           Use the `list_users` function to fetch all the IAM users.

           ```python theme={null}
           users = iam.list_users()
           ```

        3. **Check the last activity of each user:**
           For each user, you need to check their last activity. You can do this by using the `get_user` function and checking the `PasswordLastUsed` field. If this field is not present or the date is older than your threshold (e.g., 90 days), then the user is not active.

           ```python theme={null}
           for user in users['Users']:
               user_detail = iam.get_user(UserName=user['UserName'])
               if 'PasswordLastUsed' in user_detail['User']:
                   last_used = user_detail['User']['PasswordLastUsed']
                   if last_used < datetime.datetime.now(tzutc()) - datetime.timedelta(days=90):
                       print(f"User {user['UserName']} is inactive")
               else:
                   print(f"User {user['UserName']} has never logged in")
           ```

        4. **Check for access key usage:**
           Some users might not log in via the console but might use access keys instead. You need to check the last used date of all access keys of each user. If all access keys are inactive, then the user is inactive.

           ```python theme={null}
           for user in users['Users']:
               access_keys = iam.list_access_keys(UserName=user['UserName'])
               for key in access_keys['AccessKeyMetadata']:
                   last_used_response = iam.get_access_key_last_used(AccessKeyId=key['AccessKeyId'])
                   if 'LastUsedDate' in last_used_response['AccessKeyLastUsed']:
                       last_used = last_used_response['AccessKeyLastUsed']['LastUsedDate']
                       if last_used < datetime.datetime.now(tzutc()) - datetime.timedelta(days=90):
                           print(f"Access key {key['AccessKeyId']} of user {user['UserName']} is inactive")
                   else:
                       print(f"Access key {key['AccessKeyId']} of user {user['UserName']} has never been used")
           ```

        This script will print out all the users and access keys that are inactive. You can then decide what to do with these users and keys.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the issue of user accounts without any usage in AWS, you can follow the below steps:

        1. Login to your AWS account using your credentials.
        2. Go to the AWS Management Console and navigate to the IAM service.
        3. In the IAM console, click on the "Users" option from the left-hand menu.
        4. You will see a list of all the users in your AWS account.
        5. Sort the users by the "Last Activity" column to identify the users who have not used their accounts.
        6. Select the user accounts that have not been used and click on the "Delete User" button.
        7. Confirm the deletion of the user account by clicking on the "Yes, Delete" button.

        By following these steps, you can remediate the issue of user accounts without any usage in AWS.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of a user account without any usage in AWS, you can follow these steps using AWS CLI:

        1. Open the AWS CLI and run the following command to list all the users in the AWS account:

        ```
        aws iam list-users
        ```

        2. Identify the user accounts that have not been used for a long time.

        3. Run the following command to get the details of the user account:

        ```
        aws iam get-user --user-name <username>
        ```

        Replace `<username>` with the name of the user account you want to check.

        4. Check the output of the command for the `CreateDate` field. If the user account was created a long time ago and has not been used since, it can be considered for removal.

        5. Run the following command to delete the user account:

        ```
        aws iam delete-user --user-name <username>
        ```

        Replace `<username>` with the name of the user account you want to delete.

        6. Confirm the deletion by typing `yes` when prompted.

        Note: Before deleting a user account, make sure that it is not associated with any resources or services in the AWS account.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of having a user account without any usage in AWS, you can use the following steps in Python:

        1. First, you need to identify the user accounts that have not been used for a certain period of time. You can use the AWS SDK for Python (Boto3) to list all the IAM users and check their last activity date.

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

        # Set the threshold for user inactivity (e.g. 90 days)
        threshold_days = 90
        threshold_date = datetime.now() - timedelta(days=threshold_days)

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

        # Get a list of all IAM users
        users = iam.list_users()['Users']

        # Filter out the users that have been active within the threshold period
        inactive_users = []
        for user in users:
            access_keys = iam.list_access_keys(UserName=user['UserName'])['AccessKeyMetadata']
            if len(access_keys) == 0:
                last_login = user['CreateDate']
            else:
                last_login = access_keys[0]['CreateDate']
            if last_login < threshold_date:
                inactive_users.append(user['UserName'])
        ```

        2. Once you have identified the inactive users, you can remove them from the AWS account using the `delete_user` method of the IAM client.

        ```python theme={null}
        # Remove the inactive users
        for user in inactive_users:
            iam.delete_user(UserName=user)
        ```

        Note: Before removing any user, make sure to review their permissions and check if they have any active resources or services associated with them. It is also recommended to disable the user account first, rather than deleting it immediately, to allow for a grace period in case the account is still needed.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)
