> ## 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 User Password Should Be Rotated

### More Info:

Ensure that your root user password is rotated every few days.

### Risk Level

Critical

### Address

Security

### Compliance Standards

AWSWAF

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To prevent the misconfiguration where the root user should have password rotation in IAM using the AWS Management Console, follow these steps:

        1. **Sign in to the AWS Management Console:**
           * Open the AWS Management Console at [https://aws.amazon.com/console/](https://aws.amazon.com/console/).
           * Sign in using your root user credentials.

        2. **Navigate to IAM Dashboard:**
           * In the AWS Management Console, go to the **Services** menu.
           * Under **Security, Identity, & Compliance**, select **IAM** to open the IAM Dashboard.

        3. **Access Account Settings:**
           * In the IAM Dashboard, on the left-hand side, click on **Account settings**.
           * Here, you will see various security recommendations and settings for your AWS account.

        4. **Enable Password Rotation Policy:**
           * Look for the section related to **Password Policy**.
           * Ensure that the password policy enforces password rotation by setting a maximum password age. For example, set the password to expire every 90 days.
           * Save the changes to apply the new password policy.

        5. **Password Rotation:**
           * Along with **Password Rotation** Policy, rotate the password for the Root User as well.
           * Sign in using your root user credentials.
           * Go to "Security Credentials" from User Profile menu on Top Right section.
           * Click on "Update Console Password" in "AWS IAM Credentials" section.
           * Save the changes to apply the new password.

        By following these steps, you can ensure that the root user password is rotated regularly, enhancing the security of your AWS environment.
      </Accordion>

      <Accordion title="Using CLI">
        To prevent the misconfiguration where the root user should have password rotation in IAM using AWS CLI, you can follow these steps:

        1. **Create a Password Policy:**
           Ensure that a password policy is in place that enforces password rotation. This policy can specify the maximum password age, requiring users to change their passwords periodically.

           ```sh theme={null}
           aws iam update-account-password-policy --max-password-age 90
           ```

        2. **Enable MFA for Root user:**
           Enabling Multi-Factor Authentication (MFA) for the root user adds an extra layer of security, making it harder for unauthorized users to access the account even if they have the password.

           ```sh theme={null}
           aws iam enable-mfa-device --user-name root --serial-number <MFA_DEVICE_SERIAL> --authentication-code-1 <MFA_CODE_1> --authentication-code-2 <MFA_CODE_2>
           ```

        3. **Create IAM Users with Limited Permissions:**
           Instead of using the root user for daily operations, create IAM users with the necessary permissions. This reduces the risk associated with the root user.

           ```sh theme={null}
           aws iam change-password --old-password <OLD_PASSWORD> --new-password <NEW_PASSWORD>
           ```

        4. **Monitor Root user Usage:**
           Regularly monitor the usage of the root user to ensure it is not being used for routine tasks. This can be done by setting up CloudTrail to log and review root user activities.

           ```sh theme={null}
           aws cloudtrail create-trail --name <TRAIL_NAME> --s3-bucket-name <S3_BUCKET_NAME>
           aws cloudtrail start-logging --name <TRAIL_NAME>
           ```

        By following these steps, you can ensure that the root user is secured and that password rotation policies are enforced, reducing the risk of misconfigurations.
      </Accordion>

      <Accordion title="Using Python">
        To prevent the misconfiguration of not rotating the root user password 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 Python Script to Reset Password**

        Create a Python script that checks the age of the root user password. If the password is older than a specified threshold (e.g., 90 days), it will change the password.

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

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

        # Define the threshold for password age (e.g., 90 days)
        threshold_days = 90

        # Get login profile
        response = client.get_login_profile()

        # Get the last password change date
        password_last_changed = response['LoginProfile']['CreateDate']

        # Calculate the age of the password
        password_age = datetime.now() - password_last_changed

        # Check if the password age exceeds the threshold
        if password_age > timedelta(days=threshold_days):
            print("Root user password needs to be rotated.")
        else:
            print("Root user password is within the acceptable age limit.")
        ```

        By following these steps, you can effectively monitor and ensure that the root user password is rotated regularly, 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 desired user, which will take you to the "Summary" page for that user.

        4. Under "Security Credentials", check the "Password Last Used" field. If it's been a long time since the last password change, it indicates that password rotation is not being practiced for the root user.
      </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 IAM users in your AWS account:

           `aws iam list-users`

        3. Get account password policy: Use the following command to get the password policy for your AWS account:

           `aws iam get-account-password-policy`

        4. Check password rotation policy: In the output of the previous command, look for the `MaxPasswordAge` field. This field indicates the maximum number of days that an IAM user password can be used before it must be changed. If this field is not present or is set to a high value, it means that the root user does not have a password rotation policy.
      </Accordion>

      <Accordion title="Using Python">
        1. First, you need to install the AWS SDK for Python (Boto3) if you haven't done so already. You can install it using pip:

        ```python theme={null}
        pip install boto3
        ```

        2. Import the necessary modules and create a session using your AWS credentials:

        ```python theme={null}
        import boto3
        from botocore.exceptions import BotoCoreError, ClientError

        session = boto3.Session(
            aws_access_key_id='YOUR_ACCESS_KEY',
            aws_secret_access_key='YOUR_SECRET_KEY',
            aws_session_token='SESSION_TOKEN',
        )
        ```

        3. Now, create an IAM client from your session:

        ```python theme={null}
        iam = session.client('iam')
        ```

        4. To check if the root user has password rotation, you can use the `get_account_password_policy` method. If the `MaxPasswordAge` is set to a value other than `0`, it means that password rotation is enabled:

        ```python theme={null}
        try:
            response = iam.get_account_password_policy()
            if 'MaxPasswordAge' in response['PasswordPolicy']:
                if response['PasswordPolicy']['MaxPasswordAge'] != 0:
                    print("Password rotation is enabled.")
                else:
                    print("Password rotation is not enabled.")
            else:
                print("Password rotation is not enabled.")
        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchEntity':
                print("No password policy is set.")
            else:
                print("Unexpected error: %s" % e)
        ```

        This script will print whether password rotation is enabled or not. If no password policy is set, it will also print that.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "Root user Should Have Password Rotation" for AWS, follow these steps:

        1. Log in to your AWS Management Console using your Root user credentials.
        2. Click on your account name in the top right corner and select "My Security Credentials" from the dropdown menu.
        3. In the "Security Status" section, you will see a message that says "Password rotation for root user is recommended". Click on the "Rotate now" button next to it.
        4. Follow the prompts to create a new password for your Root user. Make sure to use a strong and unique password, and do not reuse any previous passwords.
        5. Once you have created a new password, click on the "Apply password policy now" button to enforce the new password policy for your Root user.
        6. You will receive a confirmation message that your Root user password has been rotated successfully.

        Congratulations, you have now remediated the misconfiguration "Root user Should Have Password Rotation" for AWS using the AWS console. It is recommended to set up a password rotation policy to ensure that your Root user password is rotated automatically on a regular basis.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate this misconfiguration for AWS using AWS CLI, follow these steps:

        1. Open the AWS CLI on your local machine and run the following command to rotate the root user password:

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

        Replace `<root_account_username>` with the username of your root user and `<new_password>` with a new, strong password.

        2. After running the above command, AWS will prompt you to reset the password the next time you log in to the root user. To do this, log in to your AWS Management Console using your root user credentials and reset the password when prompted.

        3. Once you have successfully reset the password, you should create a policy to enforce password rotation for the root user. To do this, create a JSON file with the following content:

        ```
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Sid": "AllowRootPasswordRotation",
                    "Effect": "Allow",
                    "Action": "iam:UpdateLoginProfile",
                    "Resource": "arn:aws:iam::<account_id>:user/root",
                    "Condition": {
                        "DateGreaterThan": {
                            "aws:PasswordLastUsed": "90"
                        }
                    }
                }
            ]
        }
        ```

        Replace `<account_id>` with your AWS account ID.

        4. Save the JSON file and run the following command to create a new IAM policy:

        ```
        aws iam create-policy --policy-name <policy_name> --policy-document file://<file_path>
        ```

        Replace `<policy_name>` with a name for your new policy and `<file_path>` with the path to the JSON file you created in step 3.

        5. Attach the new policy to the root user by running the following command:

        ```
        aws iam attach-user-policy --user-name <root_account_username> --policy-arn <policy_arn>
        ```

        Replace `<root_account_username>` with the username of your root user and `<policy_arn>` with the Amazon Resource Name (ARN) of the policy you created in step 4.

        6. Finally, test the policy by waiting for 90 days and then logging in to your AWS Management Console using your root user credentials. AWS will prompt you to reset the password, and you should do so to ensure that your root user password is rotated regularly.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the root user password rotation misconfiguration in AWS using Python, you can follow the below steps:

        1. Install AWS SDK for Python (boto3) using pip:

        ```
        pip install boto3
        ```

        2. Create an AWS IAM client:

        ```
        import boto3

        iam_client = boto3.client('iam')
        ```

        3. Get the current password policy:

        ```
        response = iam_client.get_account_password_policy()
        password_policy = response['PasswordPolicy']
        ```

        4. Check if password rotation is enabled for the root user:

        ```
        if password_policy['MaxPasswordAge'] is None:
            print("Password rotation is not enabled for the root user.")
        ```

        5. If password rotation is not enabled, set a new password policy with password rotation enabled:

        ```
        else:
            new_password_policy = {
                'MinimumPasswordLength': password_policy['MinimumPasswordLength'],
                'RequireSymbols': password_policy['RequireSymbols'],
                'RequireNumbers': password_policy['RequireNumbers'],
                'RequireUppercaseCharacters': password_policy['RequireUppercaseCharacters'],
                'RequireLowercaseCharacters': password_policy['RequireLowercaseCharacters'],
                'AllowUsersToChangePassword': password_policy['AllowUsersToChangePassword'],
                'MaxPasswordAge': 90, # set the maximum password age to 90 days
                'PasswordReusePrevention': password_policy['PasswordReusePrevention']
            }
            
            iam_client.update_account_password_policy(**new_password_policy)
            print("Password rotation is enabled for the root user.")
        ```

        Note: Make sure you have the necessary AWS IAM permissions to update the account password policy.
      </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)
