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

# Root Account Password Should Be Rotated

### More Info:

This rule ensures that the root account's password is regularly rotated to enhance security and minimize the risk of unauthorized access. It checks if the root account's password has been rotated within a specified time frame, typically following industry best practices and compliance requirements. Failure to rotate the root account's password regularly could increase the likelihood of unauthorized access and compromise sensitive information.

### Risk Level

High

### Address

Security

### Compliance Standards

CBP

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To prevent the misconfiguration of not rotating the root account password in AWS IAM using the AWS Management Console, follow these steps:

        1. **Enable Multi-Factor Authentication (MFA) for the Root Account:**
           * Sign in to the AWS Management Console using your root account credentials.
           * Navigate to the IAM dashboard.
           * In the left navigation pane, select "Dashboard."
           * Under "Security Status," click on "Activate MFA on your root account" and follow the instructions to enable MFA.

        2. **Set a Password Policy:**
           * In the IAM dashboard, select "Account settings" from the left navigation pane.
           * Under "Password policy," click on "Set password policy."
           * Configure the password policy to enforce strong passwords and set a maximum password age to ensure regular rotation.

        3. **Regularly Review and Rotate the Root Account Password:**
           * Periodically log in to the AWS Management Console with the root account.
           * Navigate to the "My Security Credentials" page.
           * Under "Password," click on "Manage" to change the root account password.
           * Set a reminder to rotate the root account password at regular intervals (e.g., every 90 days).

        4. **Limit Root Account Usage:**
           * Create individual IAM users with the necessary permissions for daily tasks.
           * Avoid using the root account for routine administrative tasks.
           * Use the root account only for tasks that require root privileges, such as account and billing management.

        By following these steps, you can ensure that the root account password is regularly rotated and that the root account is secured with MFA and strong password policies.
      </Accordion>

      <Accordion title="Using CLI">
        To prevent the misconfiguration of not rotating the root account password in AWS IAM using the AWS CLI, you can follow these steps:

        1. **Create an IAM User with Administrative Privileges:**
           * Instead of using the root account for daily administrative tasks, create an IAM user with administrative privileges.
           * Command:
             ```sh theme={null}
             aws iam create-user --user-name AdminUser
             aws iam attach-user-policy --user-name AdminUser --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
             ```

        2. **Enable Multi-Factor Authentication (MFA) for the Root Account:**
           * Ensure that MFA is enabled for the root account to add an extra layer of security.
           * Command:
             ```sh theme={null}
             aws iam enable-mfa-device --user-name root --serial-number <MFA_DEVICE_SERIAL_NUMBER> --authentication-code-1 <MFA_CODE_1> --authentication-code-2 <MFA_CODE_2>
             ```

        3. **Set a Password Policy for IAM Users:**
           * Enforce a strong password policy to ensure that all IAM users, including the root account, adhere to security best practices.
           * Command:
             ```sh theme={null}
             aws iam update-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
             ```

        4. **Regularly Rotate Access Keys:**
           * Regularly rotate access keys for IAM users and avoid using the root account's access keys.
           * Command to create a new access key:
             ```sh theme={null}
             aws iam create-access-key --user-name AdminUser
             ```
           * Command to delete an old access key:
             ```sh theme={null}
             aws iam delete-access-key --user-name AdminUser --access-key-id <OLD_ACCESS_KEY_ID>
             ```

        By following these steps, you can minimize the risk associated with not rotating the root account password and ensure better security practices in your AWS environment.
      </Accordion>

      <Accordion title="Using Python">
        To prevent the misconfiguration of not rotating the root account password in IAM using Python scripts, you can follow these steps:

        1. **Set Up AWS SDK (Boto3) and Required Libraries:**
           * 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 Python Script to Check Last Password Change:**
           * Write a Python script to check the last time the root account password was changed. This script will use the AWS IAM client to get the password last used information.
           ```python theme={null}
           import boto3
           from datetime import datetime, timedelta

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

           # Get account password policy
           password_policy = iam_client.get_account_password_policy()

           # Get the root account last password change date
           root_account_last_password_change = iam_client.get_user(UserName='root')['User']['PasswordLastUsed']

           # Define the maximum password age (e.g., 90 days)
           max_password_age = timedelta(days=90)

           # Check if the password needs to be rotated
           if datetime.now() - root_account_last_password_change > max_password_age:
               print("Root account password needs to be rotated.")
           else:
               print("Root account password is up to date.")
           ```

        3. **Automate the Script Execution:**
           * Schedule the script to run periodically (e.g., daily) using a task scheduler like cron (Linux) or Task Scheduler (Windows) to ensure continuous monitoring.
           * Example for cron job (Linux):
             ```bash theme={null}
             crontab -e
             ```
             Add the following line to run the script daily at midnight:
             ```bash theme={null}
             0 0 * * * /usr/bin/python3 /path/to/your_script.py
             ```

        4. **Send Notifications for Password Rotation:**
           * Enhance the script to send notifications (e.g., via email or SNS) if the root account password needs to be rotated.
           ```python theme={null}
           import boto3
           from datetime import datetime, timedelta

           # Initialize a session using Amazon IAM
           session = boto3.Session(profile_name='your-profile')
           iam_client = session.client('iam')
           sns_client = session.client('sns')

           # Get account password policy
           password_policy = iam_client.get_account_password_policy()

           # Get the root account last password change date
           root_account_last_password_change = iam_client.get_user(UserName='root')['User']['PasswordLastUsed']

           # Define the maximum password age (e.g., 90 days)
           max_password_age = timedelta(days=90)

           # Check if the password needs to be rotated
           if datetime.now() - root_account_last_password_change > max_password_age:
               message = "Root account password needs to be rotated."
               print(message)
               # Send notification
               sns_client.publish(
                   TopicArn='arn:aws:sns:your-region:your-account-id:your-topic',
                   Message=message,
                   Subject='Root Account Password Rotation Alert'
               )
           else:
               print("Root account password is up to date.")
           ```

        By following these steps, you can automate the monitoring of the root account password rotation and ensure that you are notified when it needs to be updated, thereby preventing the misconfiguration.
      </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".
        3. In the "User Name" list, choose the name of the intended user. This opens the summary page for the user.
        4. In the "Security Credential" section, check the "Password Last Used" field. If the password has not been used for a long period of time, it indicates that the root account password has not been rotated.
      </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 list of all IAM users along with their metadata.

        3. Get IAM user's password last used date: For each IAM user, you can get the date when the user's password was last used 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 the user's metadata including the `PasswordLastUsed` field.

        4. Check password last used date: Now, you can check the `PasswordLastUsed` field for each user. If this date is more than 90 days ago, it means the root account password has not been rotated in the last 90 days and this is a misconfiguration.
      </Accordion>

      <Accordion title="Using Python">
        1. First, you need to install the AWS SDK for Python (Boto3). You can do this by running the command `pip install boto3` in your terminal.

        2. Once Boto3 is installed, you can use it to interact with AWS services. To check the root account password, you need to interact with the IAM service. Here is a sample script:

        ```python theme={null}
        import boto3

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

        # Get account password policy
        try:
            response = iam.get_account_password_policy()
            print(response)
        except Exception as e:
            print("No password policy found.")
        ```

        3. This script will print out the account password policy. If there is no password policy, it will print "No password policy found."

        4. To check if the root account password should be rotated, you need to look at the 'ExpirePasswords' field in the response. If it is set to 'True', then passwords are set to expire and should be rotated. If it is 'False', then passwords do not expire and do not need to be rotated. You can add this check to the script like this:

        ```python theme={null}
        import boto3

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

        # Get account password policy
        try:
            response = iam.get_account_password_policy()
            if response['PasswordPolicy']['ExpirePasswords']:
                print("Passwords are set to expire. Root account password should be rotated.")
            else:
                print("Passwords are not set to expire. Root account password does not need to be rotated.")
        except Exception as e:
            print("No password policy found.")
        ```

        This script will now tell you whether the root account password should be rotated based on the account password policy.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the issue of Root Account Password not being rotated in AWS IAM using the AWS Management Console, follow these step-by-step instructions:

        1. **Sign in to the AWS Management Console**: Go to the AWS Management Console ([https://aws.amazon.com/](https://aws.amazon.com/)) and sign in using your root account credentials.

        2. **Navigate to the IAM Dashboard**: Once you are logged in, navigate to the IAM service by searching for it in the AWS Management Console search bar or by clicking on the "Services" dropdown menu and selecting "IAM" under the "Security, Identity, & Compliance" section.

        3. **Select the Root User**: In the IAM dashboard, click on the "Users" tab on the left-hand side. Locate and click on the root user in the list of IAM users displayed.

        4. **Rotate the Root Account Password**: In the root user details page, scroll down to the "Security credentials" section. Click on the "Manage" button next to "Console password".

        5. **Change the Root Account Password**: Click on the "Enable" button to enable the password reset. Enter a new password that meets the AWS password policy requirements (e.g., minimum length, complexity).

        6. **Save the New Password**: Click on the "Apply" button to save the new password for the root account.

        7. **Update Root Account Password Regularly**: It is recommended to set up a schedule to regularly rotate the root account password to enhance security.

        8. **Review and Confirm**: After changing the root account password, review the changes to ensure that the password has been successfully rotated.

        By following these steps, you have successfully rotated the Root Account Password in AWS IAM using the AWS Management Console, thereby remediating the misconfiguration of not rotating the root account password.
      </Accordion>

      <Accordion title="Using CLI">
        1. **Rotate Root Account Password**:
           Manually rotate the root account password through the AWS Management Console or using the AWS CLI command `aws iam change-password`.

        ```bash theme={null}
        aws iam change-password --old-password <old-password> --new-password <new-password>
        ```

        Replace `<old-password>` with the current root account password and `<new-password>` with the new password. Ensure that the password change meets the specified `minimumPasswordRotationDays`.
      </Accordion>

      <Accordion title="Using Python">
        Since the root account password cannot be programmatically rotated through the AWS SDK or CLI, the Python script won't directly rotate the password. However, you can use the following script to remind and guide users to rotate the root account password manually.

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

        def remind_root_account_password_rotation(minimum_rotation_days):
            # Check when the root account password was last changed
            iam_client = boto3.client('iam')
            response = iam_client.get_account_password_policy()
            max_password_age = response['PasswordPolicy']['MaxPasswordAge']

            root_user = iam_client.get_user(UserName='root')
            create_date = root_user['User']['CreateDate']
            password_last_changed = root_user['User'].get('PasswordLastUsed')

            if password_last_changed is None:
                print("Root account password has not been used yet.")
                return

            days_since_rotation = (datetime.now() - password_last_changed.replace(tzinfo=None)).days

            if days_since_rotation >= minimum_rotation_days:
                print("Root account password has not been rotated within the specified timeframe.")
            else:
                print("Root account password rotation is up to date.")

        def main():
            # Specify the minimum password rotation days
            minimum_rotation_days = 90  # Example: Minimum rotation period of 90 days

            # Remind users to rotate the root account password
            remind_root_account_password_rotation(minimum_rotation_days)

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

        This script checks when the root account password was last changed and reminds users to rotate the password if it hasn't been rotated within the specified `minimumPasswordRotationDays`. Adjust the `minimum_rotation_days` variable as needed.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
