> ## 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 Service Inactivity

### More Info:

Checks inactivity of any user on a service. Those priviledges should be removed for better security posture.

### Risk Level

Medium

### Address

Security

### Compliance Standards

CISAWS

### Triage and Remediation

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

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

        1. **Enable IAM Access Analyzer:**
           * Navigate to the IAM dashboard in the AWS Management Console.
           * In the left-hand navigation pane, select "Access Analyzer."
           * Click on "Create analyzer" and follow the prompts to enable IAM Access Analyzer. This tool helps you identify inactive IAM users and roles.

        2. **Set Up Password Policy:**
           * In the IAM dashboard, select "Account settings" from the left-hand navigation pane.
           * Under "Password policy," configure settings such as password expiration and password reuse prevention. This ensures that users must periodically update their passwords, reducing the risk of inactive accounts.

        3. **Enable CloudTrail Logging:**
           * Go to the CloudTrail dashboard in the AWS Management Console.
           * Click on "Create trail" and follow the prompts to enable logging for all regions.
           * Ensure that CloudTrail is configured to log IAM actions. This helps you monitor user activity and identify inactive accounts.

        4. **Set Up Automated Notifications:**
           * Navigate to the CloudWatch dashboard in the AWS Management Console.
           * Create a new rule to monitor IAM user activity.
           * Set up an alarm to trigger an SNS (Simple Notification Service) notification if a user account has been inactive for a specified period. This allows you to take proactive measures to address inactivity.

        By following these steps, you can effectively monitor and manage user account activity in AWS IAM, reducing the risk of inactive accounts.
      </Accordion>

      <Accordion title="Using CLI">
        To prevent User Account Service Inactivity in IAM using AWS CLI, you can follow these steps:

        1. **Create an IAM Policy to Enforce Password Rotation:**
           Ensure that users are required to change their passwords regularly to prevent inactivity. Create a policy that enforces password rotation.

           ```sh theme={null}
           aws iam create-account-password-policy \
               --minimum-password-length 12 \
               --require-symbols \
               --require-numbers \
               --require-uppercase-characters \
               --require-lowercase-characters \
               --allow-users-to-change-password \
               --max-password-age 90 \
               --password-reuse-prevention 5
           ```

        2. **Enable MFA for IAM Users:**
           Require Multi-Factor Authentication (MFA) for all IAM users to ensure that accounts are actively used and secured.

           ```sh theme={null}
           aws iam create-virtual-mfa-device --virtual-mfa-device-name MyVirtualMFADevice
           aws iam enable-mfa-device --user-name MyUserName --serial-number arn:aws:iam::123456789012:mfa/MyVirtualMFADevice --authentication-code1 123456 --authentication-code2 654321
           ```

        3. **Set Up CloudWatch Alarms for Inactive Users:**
           Create CloudWatch alarms to monitor and alert you when users have not logged in for a specified period.

           ```sh theme={null}
           aws cloudwatch put-metric-alarm \
               --alarm-name InactiveUserAlarm \
               --metric-name UserLogin \
               --namespace AWS/IAM \
               --statistic Sum \
               --period 86400 \
               --threshold 1 \
               --comparison-operator LessThanThreshold \
               --dimensions Name=UserName,Value=MyUserName \
               --evaluation-periods 30 \
               --alarm-actions arn:aws:sns:us-east-1:123456789012:MySNSTopic
           ```

        4. **Automate Inactive User Deactivation:**
           Use a Lambda function to automatically deactivate users who have been inactive for a specified period. This requires setting up a Lambda function and a CloudWatch event rule to trigger it.

           ```sh theme={null}
           aws lambda create-function \
               --function-name DeactivateInactiveUsers \
               --runtime python3.8 \
               --role arn:aws:iam::123456789012:role/MyLambdaRole \
               --handler lambda_function.lambda_handler \
               --zip-file fileb://function.zip

           aws events put-rule \
               --name InactiveUserCheck \
               --schedule-expression "rate(1 day)"

           aws events put-targets \
               --rule InactiveUserCheck \
               --targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:123456789012:function:DeactivateInactiveUsers"
           ```

        These steps will help you prevent user account service inactivity by enforcing password policies, enabling MFA, monitoring user activity, and automating the deactivation of inactive users.
      </Accordion>

      <Accordion title="Using Python">
        To prevent User Account Service Inactivity in IAM using Python scripts, you can follow these steps:

        ### 1. **Set Up AWS SDK (Boto3)**

        First, 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. **Create a Script to List Inactive Users**

        Create a Python script to list users who have been inactive for a specified period. This script will help you identify inactive users.

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

        # Initialize a session using Amazon IAM
        iam = boto3.client('iam')

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

        # List all IAM users
        users = iam.list_users()

        # Check for inactive users
        inactive_users = []
        for user in users['Users']:
            if 'PasswordLastUsed' in user:
                last_used = user['PasswordLastUsed']
                if last_used < threshold_date:
                    inactive_users.append(user['UserName'])

        print("Inactive users:", inactive_users)
        ```

        ### 3. **Automate Deactivation of Inactive Users**

        Modify the script to deactivate users who have been inactive for the specified period. This can be done by disabling their login profile and access keys.

        ```python theme={null}
        for user in inactive_users:
            # Deactivate login profile
            try:
                iam.delete_login_profile(UserName=user)
                print(f"Deleted login profile for user: {user}")
            except iam.exceptions.NoSuchEntityException:
                print(f"No login profile found for user: {user}")

            # Deactivate access keys
            access_keys = iam.list_access_keys(UserName=user)
            for key in access_keys['AccessKeyMetadata']:
                iam.update_access_key(UserName=user, AccessKeyId=key['AccessKeyId'], Status='Inactive')
                print(f"Deactivated access key {key['AccessKeyId']} for user: {user}")
        ```

        ### 4. **Schedule the Script to Run Periodically**

        Use a scheduling tool like cron (on Unix-based systems) or Task Scheduler (on Windows) to run the script periodically. This ensures that inactive users are regularly identified and deactivated.

        #### Example Cron Job (Unix-based systems):

        ```bash theme={null}
        # Open the crontab file
        crontab -e

        # Add the following line to run the script every day at midnight
        0 0 * * * /usr/bin/python3 /path/to/your/script.py
        ```

        By following these steps, you can automate the process of identifying and deactivating inactive IAM users using Python scripts, thereby preventing user account service inactivity in AWS IAM.
      </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 "Users". This will display a list of all the IAM users in your AWS account.

        3. Choose a user name from the list. This will open the summary page for the chosen user.

        4. In the "User Activity" section, you can see the "Last activity" information. This shows the last time the user accessed AWS services. If the "Last activity" shows "None", it means the user has not accessed any AWS services and is inactive.
      </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
           ```

           You will be prompted to provide your AWS Access Key ID, Secret Access Key, Default region name, and Default output format.

        2. List all IAM users: Once AWS CLI is set up, you can list all IAM users in your AWS account by running the following command:
           ```
           aws iam list-users
           ```
           This command will return a JSON object containing details of all IAM users.

        3. Get IAM user's last activity date: For each user, you can get the last activity date by running the following command:
           ```
           aws iam get-user --user-name <username>
           ```
           Replace `<username>` with the name of the IAM user. This command will return a JSON object containing details of the specified IAM user, including the `PasswordLastUsed` field which indicates the date and time when the IAM user last used their password for AWS Management Console or AWS CLI operations.

        4. Check for inactivity: You can then check if the `PasswordLastUsed` date is older than your inactivity threshold (for example, 90 days). If it is, then the IAM user is considered inactive. You can do this check manually or write a script to automate the process.
      </Accordion>

      <Accordion title="Using Python">
        1. **Import necessary libraries and establish a connection with AWS IAM:**
           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, and others. After importing the necessary libraries, establish a connection with AWS IAM.

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

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

        2. **Fetch all the users:**
           Use the `list_users()` function to fetch all the users. This function returns a list of IAM users for the AWS account.

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

        3. **Check the last activity of each user:**
           For each user, fetch the access key details using the `list_access_keys()` function. This function returns metadata about the access keys associated with the specified IAM user. If the user has not used their access key for a certain period, flag them as inactive.

           ```python theme={null}
           # Define the inactivity period (e.g., 90 days)
           inactivity_period = datetime.timedelta(days=90)

           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'])
                   last_used_date = last_used_response['AccessKeyLastUsed']['LastUsedDate']

                   if (datetime.datetime.now(tzutc()) - last_used_date) > inactivity_period:
                       print(f"User {user['UserName']} is inactive.")
           ```

        4. **Interpret the results:**
           The script will print the usernames of all users who have not used their access keys for more than the specified inactivity period. If no such users are found, the script will not print anything. This script can be run periodically to monitor user activity and detect any inactive users.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the User Account Service Inactivity issue in AWS using the AWS console, you can follow these steps:

        1. Log in to your AWS Management Console.
        2. Go to the IAM service.
        3. Click on the "Users" option in the left-hand menu.
        4. Select the user account that has been inactive.
        5. Click on the "Security credentials" tab.
        6. Under "Console password", click on "Manage".
        7. Follow the prompts to reset the user's password.
        8. Click on the "Access keys" tab.
        9. Delete any access keys that have not been used in the last 90 days.
        10. Click on the "Permissions" tab.
        11. Review the user's permissions and remove any that are no longer necessary.
        12. Click on the "Groups" tab.
        13. Review the groups the user is a member of and remove any that are no longer necessary.
        14. Click on the "Policies" tab.
        15. Review the policies attached to the user and remove any that are no longer necessary.
        16. Click on "Apply" to save the changes.

        These steps will remediate the User Account Service Inactivity issue in AWS by resetting the user's password, deleting unused access keys, reviewing and removing unnecessary permissions, groups, and policies.

        #
      </Accordion>

      <Accordion title="Using CLI">
        The following steps can be taken to remediate the User Account Service Inactivity misconfiguration in AWS using AWS CLI:

        1. Open the AWS CLI on your local machine or EC2 instance.

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

           ```
           aws iam list-users
           ```

        3. Identify the inactive users from the list. Inactive users are those who have not logged in to their AWS account for a specified number of days.

        4. To set a password policy, run the following command:

           ```
           aws iam update-account-password-policy --minimum-password-length 8 --require-symbols --require-numbers --require-uppercase-characters --require-lowercase-characters --allow-users-to-change-password --max-password-age 90 --password-reuse-prevention 5
           ```

           This command will set a password policy for your AWS account. You can modify the parameters as per your requirement.

        5. To force an IAM user to reset their password on next login, run the following command:

           ```
           aws iam update-login-profile --user-name <user-name> --password-reset-required
           ```

           Replace `<user-name>` with the name of the inactive user. This command will force the user to reset their password on their next login.

        6. Repeat steps 4 and 5 for all the inactive users in your AWS account.

        7. Finally, run the following command to verify that the password policy has been updated successfully:

           ```
           aws iam get-account-password-policy
           ```

           This command will display the current password policy for your AWS account.

        By following these steps, you can remediate the User Account Service Inactivity misconfiguration in AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the User Account Service Inactivity misconfiguration in AWS using Python, you can follow these steps:

        1. First, you need to identify the user accounts that have been inactive for a specified period. You can use the boto3 library in Python to interact with AWS services.

        ```
        import boto3
        from datetime import datetime, timedelta

        # Set the time period for inactivity
        inactivity_period = 90

        # Create a boto3 client for AWS IAM
        iam = boto3.client('iam')

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

        # Iterate over each user and check their last activity date
        for user in users:
            # Get the user's access keys
            access_keys = iam.list_access_keys(UserName=user['UserName'])['AccessKeyMetadata']
            
            # Check if any access keys are active
            for key in access_keys:
                if key['Status'] == 'Active':
                    # Get the last time the access key was used
                    last_used = iam.get_access_key_last_used(AccessKeyId=key['AccessKeyId'])['AccessKeyLastUsed']['LastUsedDate']
                    
                    # Check if the access key has been inactive for the specified period
                    if last_used < datetime.now() - timedelta(days=inactivity_period):
                        # The access key has been inactive for too long, disable it
                        iam.update_access_key(AccessKeyId=key['AccessKeyId'], Status='Inactive')
        ```

        2. The code above will disable the access keys for any user that has been inactive for the specified period. You can adjust the inactivity\_period variable to suit your needs.

        3. You can schedule this script to run periodically using a cron job or a similar scheduling tool. This will ensure that any inactive access keys are disabled automatically.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_finding-unused.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_finding-unused.html)
