> ## 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 Access Keys Should Be Rotated

### More Info:

Root account should not have access keys. If at all you have that, then the keys should be rotated periodically.

### Risk Level

Medium

### Address

Security

### Compliance Standards

HIPAA, ISO27001, CISAWS, CBP

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To prevent the issue of root account access keys needing rotation in AWS IAM using the AWS Management Console, follow these steps:

        1. **Navigate to IAM Dashboard:**
           * Sign in to the AWS Management Console.
           * In the navigation bar, select "Services" and then choose "IAM" to open the IAM Dashboard.

        2. **Access the Root Account Security Settings:**
           * In the IAM Dashboard, click on the "Dashboard" link in the left-hand navigation pane.
           * Look for the "Security Status" section and click on "Manage Security Credentials" under the "Root Account" heading.

        3. **Review Access Keys:**
           * In the "Security Credentials" page, scroll down to the "Access keys" section.
           * Check the status and last used date of any existing access keys for the root account.

        4. **Delete or Disable Root Access Keys:**
           * If access keys are present, consider deleting or disabling them to prevent their use. Click on the "Delete" button next to each access key to remove it.
           * Alternatively, if you need to keep the access keys, ensure they are rotated regularly by setting up a reminder or using an automated tool to manage key rotation.

        By following these steps, you can help ensure that root account access keys are managed securely and rotated as needed to maintain the security of your AWS environment.
      </Accordion>

      <Accordion title="Using CLI">
        To prevent the issue of root account access keys not being rotated in AWS IAM using the AWS CLI, you can follow these steps:

        1. **Create IAM User for Administrative Tasks:**
           * 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
             ```

        2. **Attach Administrative Policies to the IAM User:**
           * Attach the necessary policies to the IAM user to grant administrative privileges.
           * Command:
             ```sh theme={null}
             aws iam attach-user-policy --user-name AdminUser --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
             ```

        3. **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 (Note: This step requires manual intervention to complete the MFA setup):
             ```sh theme={null}
             aws iam enable-mfa-device --user-name root --serial-number <MFA_DEVICE_SERIAL> --authentication-code1 <MFA_CODE1> --authentication-code2 <MFA_CODE2>
             ```

        4. **Delete Existing Root Access Keys:**
           * Remove any existing access keys for the root account to prevent their use.
           * Command:
             ```sh theme={null}
             aws iam list-access-keys --user-name root
             aws iam delete-access-key --user-name root --access-key-id <ACCESS_KEY_ID>
             ```

        By following these steps, you can prevent the use of root account access keys and ensure that administrative tasks are performed using IAM users with appropriate permissions.
      </Accordion>

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

        1. **Set Up AWS SDK for Python (Boto3):**
           * 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 Root Access Key Age:**

           * Write a Python script that uses Boto3 to check the age of the root access keys. If the keys are older than a specified threshold (e.g., 90 days), the script can alert you or take action to rotate them.

           ```python theme={null}
           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 threshold for key age (e.g., 90 days)
           threshold_days = 90
           threshold_date = datetime.now() - timedelta(days=threshold_days)

           # Get the root account access keys
           response = iam_client.list_access_keys(UserName='root')

           for access_key in response['AccessKeyMetadata']:
               access_key_id = access_key['AccessKeyId']
               create_date = access_key['CreateDate']

               # Check if the access key is older than the threshold
               if create_date < threshold_date:
                   print(f"Access key {access_key_id} is older than {threshold_days} days and should be rotated.")
                   # Here you can add logic to alert or rotate the key
           ```

        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 cron job to run the script daily at midnight:

           ```bash theme={null}
           0 0 * * * /usr/bin/python3 /path/to/your_script.py
           ```

        4. **Implement Key Rotation Logic (Optional):**

           * If you want to automate the rotation process, you can extend the script to deactivate the old key and create a new one. Ensure you securely store the new key and update any systems that use it.

           ```python theme={null}
           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 threshold for key age (e.g., 90 days)
           threshold_days = 90
           threshold_date = datetime.now() - timedelta(days=threshold_days)

           # Get the root account access keys
           response = iam_client.list_access_keys(UserName='root')

           for access_key in response['AccessKeyMetadata']:
               access_key_id = access_key['AccessKeyId']
               create_date = access_key['CreateDate']

               # Check if the access key is older than the threshold
               if create_date < threshold_date:
                   print(f"Access key {access_key_id} is older than {threshold_days} days and should be rotated.")
                   
                   # Deactivate the old key
                   iam_client.update_access_key(UserName='root', AccessKeyId=access_key_id, Status='Inactive')
                   
                   # Create a new access key
                   new_key_response = iam_client.create_access_key(UserName='root')
                   new_access_key_id = new_key_response['AccessKey']['AccessKeyId']
                   new_secret_access_key = new_key_response['AccessKey']['SecretAccessKey']
                   
                   print(f"New access key created: {new_access_key_id}")
                   # Securely store the new access key and secret access key
                   # Update any systems that use the old key with the new key
           ```

        By following these steps, you can effectively monitor and manage the rotation of root account access keys using Python scripts.
      </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. In the "Security Credentials" section, you can see the access keys and their status. If the access keys are older than 90 days, it indicates that they have not been rotated and this is a misconfiguration.
      </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 --query 'Users[*].UserName' --output text`

        3. For each user, list all access keys: For each IAM user, you can list all their access keys using the following command:

           `aws iam list-access-keys --user-name <username>`

           Replace `<username>` with the actual username.

        4. Check the age of each access key: For each access key, you can check its age using the following command:

           `aws iam get-access-key-last-used --access-key-id <accessKeyId>`

           Replace `<accessKeyId>` with the actual access key ID. The `CreateDate` field in the output indicates when the access key was last rotated. If it's more than 90 days old, it's a misconfiguration.
      </Accordion>

      <Accordion title="Using Python">
        1. First, you need to install the AWS SDK for Python (Boto3). 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 ClientError

        # Create a session using your AWS credentials
        session = boto3.Session(
            aws_access_key_id='YOUR_ACCESS_KEY',
            aws_secret_access_key='YOUR_SECRET_KEY',
            region_name='us-west-2'
        )
        ```

        3. Create an IAM client and retrieve all the users:

        ```python theme={null}
        # Create an IAM client
        iam = session.client('iam')

        # Retrieve all users
        try:
            users = iam.list_users()
        except ClientError as e:
            print(f"Unexpected error: {e}")
        ```

        4. For each user, retrieve the access keys and check the creation date. If the creation date is older than 90 days, print a warning message:

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

        # Check each user
        for user in users['Users']:
            # Retrieve the access keys
            access_keys = iam.list_access_keys(UserName=user['UserName'])

            # Check each access key
            for key in access_keys['AccessKeyMetadata']:
                # Calculate the age of the key
                age = datetime.now(tz=key['CreateDate'].tzinfo) - key['CreateDate']

                # If the key is older than 90 days, print a warning
                if age > timedelta(days=90):
                    print(f"WARNING: The access key {key['AccessKeyId']} for user {user['UserName']} is {age.days} days old and should be rotated.")
        ```

        This script will help you detect if any IAM user's access keys are older than 90 days and should be rotated.
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of root account access keys should be rotated in AWS using the AWS console, follow these steps:

        1. Login to the AWS Management Console using root account credentials.
        2. Go to the IAM dashboard by selecting "Services" from the top navigation bar and selecting "IAM" under the "Security, Identity & Compliance" category.
        3. In the IAM dashboard, select "Users" from the left-hand menu and locate the root account user.
        4. Click on the root account user to view the details.
        5. In the "Security credentials" tab, locate the "Access keys" section and click on "Rotate access key."
        6. A dialog box will appear asking you to confirm the rotation of the access keys. Click on "Rotate."
        7. The console will generate a new access key pair. Download the new access key and secret key and store them securely.
        8. After downloading the new access keys, delete the old access keys by clicking on the "X" next to the key.
        9. Repeat this process periodically to ensure that the root account access keys are regularly rotated.

        By following these steps, you can remediate the misconfiguration of root account access keys should be rotated in AWS using the AWS console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the issue of Root Account Access Keys Should Be Rotated in AWS using AWS CLI, follow these steps:

        1. Open the AWS CLI on your local machine.

        2. Run the following command to list all the access keys associated with the root account:

           ```
           aws iam list-access-keys --user-name <root_account_user_name>
           ```

           Replace `<root_account_user_name>` with the name of your root account user.

        3. Identify the access key that needs to be rotated.

        4. Run the following command to create a new access key:

           ```
           aws iam create-access-key --user-name <root_account_user_name>
           ```

           This command will create a new access key and secret access key pair.

        5. Run the following command to delete the old access key:

           ```
           aws iam delete-access-key --user-name <root_account_user_name> --access-key-id <old_access_key_id>
           ```

           Replace `<old_access_key_id>` with the access key ID of the old access key that needs to be rotated.

        6. Update any scripts or applications that use the old access key with the new access key.

        7. Verify that the new access key is working properly by running a test command.

           ```
           aws s3 ls
           ```

           This command should list all the S3 buckets in your account.

        8. Repeat steps 3-7 for any other access keys associated with the root account.

        9. Once all the access keys have been rotated, ensure that the root account password is also strong and has been rotated recently.

        By following these steps, you can remediate the issue of Root Account Access Keys Should Be Rotated in AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of Root Account Access Keys Should Be Rotated in AWS using Python, follow these steps:

        1. Install the AWS SDK for Python (Boto3) using pip.

        ```
        pip install boto3
        ```

        2. Create an AWS IAM client using Boto3.

        ```
        import boto3

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

        3. Get the list of access keys for the root account.

        ```
        # Get the list of access keys for the root account
        response = iam.list_access_keys(UserName='root')
        access_key_list = response['AccessKeyMetadata']
        ```

        4. Loop through the access keys and check the age of each key. If an access key is older than 90 days, create a new key and delete the old key.

        ```
        # Loop through the access keys and check the age of each key
        for access_key in access_key_list:
            access_key_id = access_key['AccessKeyId']
            create_date = access_key['CreateDate']
            age = (datetime.now(create_date.tzinfo) - create_date).days

            # If an access key is older than 90 days, create a new key and delete the old key
            if age > 90:
                new_access_key = iam.create_access_key(UserName='root')['AccessKey']
                iam.delete_access_key(UserName='root', AccessKeyId=access_key_id)
        ```

        5. Save the Python script and run it periodically to ensure that the root account access keys are rotated every 90 days.

        Note: It is recommended to use AWS Identity and Access Management (IAM) roles instead of root account access keys for accessing AWS services.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html)
