> ## 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 Activity Should Be Monitored

### More Info:

Checks activity of any root user . Using the root account is strongly discouraged for everyday tasks as it carries a high level of privilege and can be risky.  Monitoring this activity can help ensure the root account is only being used for authorized purposes.

### Risk Level

Medium

### Address

Security

### Compliance Standards

CBP

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To prevent root account activity from going unmonitored in AWS IAM using the AWS Management Console, follow these steps:

        1. **Enable CloudTrail for All Regions:**
           * Go to the AWS Management Console.
           * Navigate to the CloudTrail service.
           * Create a new trail or edit an existing one.
           * Ensure that the trail is enabled for all regions to capture all root account activities across your AWS environment.

        2. **Set Up CloudWatch Alarms for Root Account Usage:**
           * Go to the CloudWatch service in the AWS Management Console.
           * Create a new alarm.
           * Set the metric to monitor root account usage (e.g., `AWS/CloudTrail` metric for `RootAccountUsage`).
           * Configure the alarm to send notifications (e.g., via SNS) when root account activity is detected.

        3. **Enable AWS Config Rules:**
           * Navigate to the AWS Config service in the AWS Management Console.
           * Ensure that AWS Config is enabled and recording.
           * Add a managed rule such as `root-account-mfa-enabled` to ensure that root account activity is monitored and that MFA is enabled for the root account.

        4. **Set Up SNS Notifications for Root Account Activity:**
           * Go to the SNS (Simple Notification Service) in the AWS Management Console.
           * Create a new SNS topic.
           * Subscribe your email or SMS to the topic.
           * Configure CloudTrail or CloudWatch to send notifications to this SNS topic whenever root account activity is detected.

        By following these steps, you can ensure that any activity involving the root account is closely monitored, helping to maintain the security and integrity of your AWS environment.
      </Accordion>

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

        1. **Enable CloudTrail for Logging:**
           Ensure that AWS CloudTrail is enabled to log all activities, including those performed by the root account.
           ```sh theme={null}
           aws cloudtrail create-trail --name my-trail --s3-bucket-name my-trail-bucket
           aws cloudtrail start-logging --name my-trail
           ```

        2. **Set Up CloudWatch Alarms for Root Account Usage:**
           Create a CloudWatch alarm to monitor root account activity. First, create a metric filter to capture root account usage from CloudTrail logs.
           ```sh theme={null}
           aws logs create-log-group --log-group-name CloudTrail/DefaultLogGroup
           aws logs create-log-stream --log-group-name CloudTrail/DefaultLogGroup --log-stream-name RootAccountUsage
           aws logs put-metric-filter --log-group-name CloudTrail/DefaultLogGroup --filter-name RootAccountUsageFilter --filter-pattern '{ $.userIdentity.type = "Root" }' --metric-transformations metricName=RootAccountUsage,metricNamespace=CloudTrailMetrics,metricValue=1
           ```

        3. **Create CloudWatch Alarm:**
           Create an alarm based on the metric filter to notify you when root account activity is detected.
           ```sh theme={null}
           aws cloudwatch put-metric-alarm --alarm-name RootAccountUsageAlarm --metric-name RootAccountUsage --namespace CloudTrailMetrics --statistic Sum --period 300 --threshold 1 --comparison-operator GreaterThanOrEqualToThreshold --evaluation-periods 1 --alarm-actions arn:aws:sns:us-east-1:123456789012:MySNSTopic
           ```

        4. **Subscribe to SNS Topic for Notifications:**
           Ensure you have an SNS topic to receive notifications and subscribe to it.
           ```sh theme={null}
           aws sns create-topic --name MySNSTopic
           aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:MySNSTopic --protocol email --notification-endpoint myemail@example.com
           ```

        By following these steps, you can effectively monitor root account activity in AWS IAM using the AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To prevent root account activity from going unmonitored in AWS IAM using Python scripts, you can follow these steps:

        ### 1. Enable CloudTrail for Root Account Activity

        CloudTrail is a service that enables governance, compliance, and operational and risk auditing of your AWS account. By enabling CloudTrail, you can log, continuously monitor, and retain account activity related to actions across your AWS infrastructure.

        ```python theme={null}
        import boto3

        def enable_cloudtrail():
            client = boto3.client('cloudtrail')
            response = client.create_trail(
                Name='RootAccountActivityTrail',
                S3BucketName='your-s3-bucket-name',
                IncludeGlobalServiceEvents=True,
                IsMultiRegionTrail=True,
                EnableLogFileValidation=True,
                IsOrganizationTrail=False
            )
            client.start_logging(Name='RootAccountActivityTrail')
            print("CloudTrail enabled and logging started for root account activity.")

        enable_cloudtrail()
        ```

        ### 2. Set Up CloudWatch Alarms for Root Account Activity

        CloudWatch can be used to set up alarms that notify you when specific actions are taken by the root account.

        ```python theme={null}
        import boto3

        def create_cloudwatch_alarm():
            client = boto3.client('cloudwatch')
            response = client.put_metric_alarm(
                AlarmName='RootAccountActivityAlarm',
                MetricName='RootAccountUsage',
                Namespace='AWS/CloudTrail',
                Statistic='Sum',
                Period=300,
                EvaluationPeriods=1,
                Threshold=1,
                ComparisonOperator='GreaterThanOrEqualToThreshold',
                AlarmActions=[
                    'arn:aws:sns:your-region:your-account-id:your-sns-topic'
                ],
                Dimensions=[
                    {
                        'Name': 'EventName',
                        'Value': 'ConsoleLogin'
                    },
                    {
                        'Name': 'UserIdentity.arn',
                        'Value': 'arn:aws:iam::your-account-id:root'
                    }
                ]
            )
            print("CloudWatch alarm created for root account activity.")

        create_cloudwatch_alarm()
        ```

        ### 3. Enable Multi-Factor Authentication (MFA) for Root Account

        Enabling MFA adds an extra layer of security to your root account. This script ensures that MFA is enabled for the root account.

        ```python theme={null}
        import boto3

        def enable_mfa_for_root():
            client = boto3.client('iam')
            response = client.create_virtual_mfa_device(
                VirtualMFADeviceName='root-account-mfa',
                Path='/',
            )
            print("MFA device created for root account. Please manually associate it with the root account.")

        enable_mfa_for_root()
        ```

        ### 4. Restrict Root Account Usage

        Create an IAM policy that restricts the usage of the root account and apply it to all users.

        ```python theme={null}
        import boto3

        def create_restrict_root_policy():
            client = boto3.client('iam')
            policy_document = {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Deny",
                        "Action": "*",
                        "Resource": "*",
                        "Condition": {
                            "StringEquals": {
                                "aws:username": "root"
                            }
                        }
                    }
                ]
            }
            response = client.create_policy(
                PolicyName='RestrictRootAccountUsage',
                PolicyDocument=json.dumps(policy_document)
            )
            print("Policy created to restrict root account usage.")

        create_restrict_root_policy()
        ```

        These steps will help you monitor and restrict root account activity, ensuring that any actions taken by the root account are logged, monitored, and controlled.
      </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 "Credential Report". This report will list all your account's users and the status of their various credentials.

        3. If the report is not ready, choose "Download Report". This will generate a new report.

        4. Open the report and look for the root account. Check the "password\_last\_used" or "access\_key\_1\_last\_used\_date" columns. If these columns show a recent date, it means the root account has been used recently.
      </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. You can download it from the official AWS website. After installation, you need to configure it with your AWS account credentials. You can do this by running the command `aws configure` and then entering your Access Key ID, Secret Access Key, Default region name, and Default output format when prompted.

        2. List all IAM users: To check the activity of the root account, you first need to list all IAM users. You can do this by running the command `aws iam list-users`. This will return a list of all IAM users in your AWS account.

        3. Check last used access key: To check when the root account was last used, you can use the command `aws iam get-access-key-last-used --access-key-id <access-key-id>`. Replace `<access-key-id>` with the access key ID of the root account. This will return the date and time when the root account was last used.

        4. Check CloudTrail logs: AWS CloudTrail logs all API calls made in your AWS account. You can use these logs to monitor the activity of the root account. To do this, you can use the command `aws cloudtrail lookup-events --lookup-attributes AttributeKey=Username,AttributeValue=root`. This will return a list of all API calls made by the root account.
      </Accordion>

      <Accordion title="Using Python">
        1. Install the necessary Python libraries: Before you can start writing the script, you need to install the necessary Python libraries. The AWS SDK for Python (Boto3) allows Python developers to write software that makes use of services like Amazon S3, Amazon EC2, etc. You can install it using pip:

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

        2. Configure AWS Credentials: You need to configure your AWS credentials. You can configure credentials by using the AWS CLI or by directly adding them to your script. However, it's not a good practice to hard code your credentials into your script.

        ```python theme={null}
        import boto3

        aws_access_key_id = 'YOUR_ACCESS_KEY'
        aws_secret_access_key = 'YOUR_SECRET_KEY'
        aws_session_token = 'YOUR_SESSION_TOKEN'

        session = boto3.Session(
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key,
            aws_session_token=aws_session_token,
        )
        ```

        3. Write a Python script to check Root Account Activity: You can use the AWS CloudTrail service to monitor the root account activity. CloudTrail provides event history of your AWS account activity, including actions taken through the AWS Management Console, AWS SDKs, command line tools, and other AWS services.

        ```python theme={null}
        import boto3

        def check_root_account_activity():
            client = boto3.client('cloudtrail')
            response = client.lookup_events(
                LookupAttributes=[
                    {
                        'AttributeKey': 'Username',
                        'AttributeValue': 'root'
                    },
                ],
                MaxResults=1
            )
            if 'Events' in response and len(response['Events']) > 0:
                print("Root account activity detected.")
            else:
                print("No root account activity detected.")

        check_root_account_activity()
        ```

        4. Run the Python script: Finally, you can run the Python script to check if there is any root account activity. If there is any activity, it will print "Root account activity detected." Otherwise, it will print "No root account activity detected."
      </Accordion>
    </AccordionGroup>
  </Tab>

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of not monitoring root account activity in AWS IAM using the AWS Management Console, follow these step-by-step instructions:

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

        2. **Navigate to CloudTrail**: In the AWS Management Console, search for "CloudTrail" in the services search bar and click on the CloudTrail service.

        3. **Create a new trail**: Click on the "Trails" option in the left-hand navigation pane, then click on the "Create trail" button.

        4. **Configure trail settings**:
           * Enter a name for the trail (e.g., "RootAccountMonitoring").
           * Choose the S3 bucket where you want to store the CloudTrail logs.
           * Enable the option for "Read/Write events".
           * Click on "Create" to create the trail.

        5. **Enable logging for the root account**: By default, CloudTrail logs all AWS account activity, including actions performed by the root account.

        6. **Set up CloudWatch alarms** (optional): You can set up CloudWatch alarms to monitor specific API activity related to the root account. This can help you detect suspicious activity and respond quickly.

        7. **Review and monitor the logs**: Regularly review the CloudTrail logs to monitor the activity of the root account and detect any unauthorized actions.

        By following these steps, you can remediate the misconfiguration of not monitoring root account activity in AWS IAM using the AWS Management Console and enhance the security of your AWS account.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of not monitoring root account activity in AWS IAM using AWS CLI, follow these steps:

        1. **Enable CloudTrail logging for the AWS account**:
           * Run the following AWS CLI command to enable CloudTrail logging:
             ```
             aws cloudtrail create-trail --name <trail-name> --s3-bucket-name <bucket-name> --is-multi-region-trail
             ```
             Replace `<trail-name>` with a suitable name for the CloudTrail trail, and `<bucket-name>` with the name of the S3 bucket where CloudTrail logs will be stored.

        2. **Enable logging for AWS Management Console sign-in events**:
           * Run the following AWS CLI command to enable logging for AWS Management Console sign-in events:
             ```
             aws cloudtrail update-trail --name <trail-name> --enable-log-file-validation
             ```

        3. **Configure CloudWatch Events for monitoring root account activity**:
           * Create a CloudWatch Events rule to monitor root account activity by running the following AWS CLI command:
             ```
             aws events put-rule --name MonitorRootAccountActivity --event-pattern "{\"source\": [\"aws.iam\"],\"detail-type\": [\"AWS API Call via CloudTrail\"],\"detail\":{\"userIdentity\":{\"type\":[\"Root\"]}}"
             ```

        4. **Create a target for the CloudWatch Events rule**:
           * Create a target for the CloudWatch Events rule to specify the action to be taken when the rule is triggered. For example, you can send an SNS notification by running the following AWS CLI command:
             ```
             aws events put-targets --rule MonitorRootAccountActivity --targets "Id"="1","Arn"="<sns-topic-arn>"
             ```
             Replace `<sns-topic-arn>` with the ARN of the SNS topic where notifications will be sent.

        5. **Enable the CloudWatch Events rule**:
           * Enable the CloudWatch Events rule to start monitoring root account activity by running the following AWS CLI command:
             ```
             aws events enable-rule --name MonitorRootAccountActivity
             ```

        By following these steps, you will successfully remediate the misconfiguration of not monitoring root account activity in AWS IAM using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of not monitoring root account activity in AWS IAM using Python, you can follow these steps:

        1. **Enable AWS CloudTrail for Root Account Activity Logging:**

           * Use the AWS SDK for Python (Boto3) to enable CloudTrail logging for the root account. Here's an example code snippet to enable CloudTrail logging:

           ```python theme={null}
           import boto3

           client = boto3.client('cloudtrail')

           response = client.update_trail(
               Name='your-cloudtrail-name',
               IncludeGlobalServiceEvents=True,
               IsMultiRegionTrail=True,
               EnableLogFileValidation=True
           )
           ```

        2. **Set Up CloudWatch Alarms for Root Account Activity:**

           * Use Boto3 to create CloudWatch alarms that monitor root account activity. Here's an example code snippet to create a CloudWatch alarm for monitoring root account sign-in events:

           ```python theme={null}
           import boto3

           client = boto3.client('cloudwatch')

           response = client.put_metric_alarm(
               AlarmName='RootAccountSignInAlarm',
               ComparisonOperator='GreaterThanThreshold',
               EvaluationPeriods=1,
               MetricName='SigninSuccesses',
               Namespace='AWS/CloudTrail',
               Period=300,
               Statistic='Sum',
               Threshold=0.0,
               ActionsEnabled=True,
               AlarmDescription='Alarm for Root Account Sign-In Events',
               Dimensions=[
                   {
                       'Name': 'EventName',
                       'Value': 'ConsoleLogin'
                   },
                   {
                       'Name': 'Username',
                       'Value': 'root'
                   }
               ],
               AlarmActions=[
                   'arn:aws:sns:your-region:your-account-id:your-sns-topic'
               ]
           )
           ```

        3. **Configure SNS Topic for CloudWatch Alarms:**

           * You need to create an SNS topic and subscribe to it to receive notifications for CloudWatch alarms. Here's an example code snippet to create an SNS topic:

           ```python theme={null}
           import boto3

           client = boto3.client('sns')

           response = client.create_topic(
               Name='RootAccountActivityTopic'
           )

           topic_arn = response['TopicArn']

           response = client.subscribe(
               TopicArn=topic_arn,
               Protocol='email',
               Endpoint='your-email@example.com'
           )
           ```

        By following these steps and regularly monitoring the CloudTrail logs and CloudWatch alarms, you can effectively remediate the misconfiguration of not monitoring root account activity in AWS IAM using Python.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
