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
- APRA CPS 234 (Australia)
- BSI C5 (Germany)
- Brazil LGPD
- CCPA / CPRA (California)
- CIS Critical Security Controls v8
- CMMC 2.0
- CSA Cloud Controls Matrix v4
- Cloudanix Best Practice
- DPDPA
- Digital Operational Resilience Act (EU)
- Essential 8
- ISO/IEC 27017
- ISO/IEC 27018
- ISO/IEC 27701
- KSA PDPL
- MAS Technology Risk Management (Singapore)
- MITRE ATT&CK (Cloud)
- NIS2 Directive
- NIST SP 800-171
- NYDFS 23 NYCRR 500
- SWIFT Customer Security Controls Framework
- Sarbanes-Oxley IT General Controls
- UK NCSC Cyber Assessment Framework
Triage and Remediation
- Prevention
- Cause
- Remediation
How to Prevent
Using Console
To prevent root account activity from going unmonitored in AWS IAM using the AWS Management Console, follow these steps:
-
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.
-
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/CloudTrailmetric forRootAccountUsage). - Configure the alarm to send notifications (e.g., via SNS) when root account activity is detected.
-
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-enabledto ensure that root account activity is monitored and that MFA is enabled for the root account.
-
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.
Using CLI
To prevent the misconfiguration of not monitoring root account activity in AWS IAM using the AWS CLI, you can follow these steps:
-
Enable CloudTrail for Logging: Ensure that AWS CloudTrail is enabled to log all activities, including those performed by the root account.
aws cloudtrail create-trail --name my-trail --s3-bucket-name my-trail-bucketaws cloudtrail start-logging --name my-trail -
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.
aws logs create-log-group --log-group-name CloudTrail/DefaultLogGroupaws logs create-log-stream --log-group-name CloudTrail/DefaultLogGroup --log-stream-name RootAccountUsageaws 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 -
Create CloudWatch Alarm: Create an alarm based on the metric filter to notify you when root account activity is detected.
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 -
Subscribe to SNS Topic for Notifications: Ensure you have an SNS topic to receive notifications and subscribe to it.
aws sns create-topic --name MySNSTopicaws 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.
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.
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.
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.
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.
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.
Check Cause
Using Console
-
Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.
-
In the navigation pane, choose "Credential Report". This report will list all your account's users and the status of their various credentials.
-
If the report is not ready, choose "Download Report". This will generate a new report.
-
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.
Using CLI
-
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 configureand then entering your Access Key ID, Secret Access Key, Default region name, and Default output format when prompted. -
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. -
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. -
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.
Using Python
- 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:
pip install boto3
- 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.
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,
)
- 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.
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()
- 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."
Remediation
Using Console
To remediate the misconfiguration of not monitoring root account activity in AWS IAM using the AWS Management Console, follow these step-by-step instructions:
-
Sign in to the AWS Management Console: Go to https://aws.amazon.com/ and sign in to your AWS account using your root account credentials.
-
Navigate to CloudTrail: In the AWS Management Console, search for "CloudTrail" in the services search bar and click on the CloudTrail service.
-
Create a new trail: Click on the "Trails" option in the left-hand navigation pane, then click on the "Create trail" button.
-
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.
-
Enable logging for the root account: By default, CloudTrail logs all AWS account activity, including actions performed by the root account.
-
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.
-
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.
Using CLI
To remediate the misconfiguration of not monitoring root account activity in AWS IAM using AWS CLI, follow these steps:
-
Enable CloudTrail logging for the AWS account:
- Run the following AWS CLI command to enable CloudTrail logging:
Replaceaws cloudtrail create-trail --name <trail-name> --s3-bucket-name <bucket-name> --is-multi-region-trail
<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.
- Run the following AWS CLI command to enable CloudTrail logging:
-
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
- Run the following AWS CLI command to enable logging for AWS Management Console sign-in events:
-
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\"]}}"
- Create a CloudWatch Events rule to monitor root account activity by running the following AWS CLI command:
-
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:
Replaceaws events put-targets --rule MonitorRootAccountActivity --targets "Id"="1","Arn"="<sns-topic-arn>"
<sns-topic-arn>with the ARN of the SNS topic where notifications will be sent.
- 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:
-
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
- Enable the CloudWatch Events rule to start monitoring root account activity by running the following AWS CLI command:
By following these steps, you will successfully remediate the misconfiguration of not monitoring root account activity in AWS IAM using AWS CLI.
Using Python
To remediate the misconfiguration of not monitoring root account activity in AWS IAM using Python, you can follow these steps:
-
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:
import boto3client = boto3.client('cloudtrail')response = client.update_trail(Name='your-cloudtrail-name',IncludeGlobalServiceEvents=True,IsMultiRegionTrail=True,EnableLogFileValidation=True) -
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:
import boto3client = 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']) -
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:
import boto3client = 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.
Using Terraform
# This finding cannot be remediated on aws_iam_user: the AWS root account is
# NOT an IAM user and has no corresponding aws_iam_user resource in Terraform.
#
# Monitoring root activity is configured at the account/logging level
# (CloudTrail + CloudWatch), not on an IAM user object.
# Example of where this is actually configured in Terraform (not on aws_iam_user):
resource "aws_cloudtrail" "root_activity_trail" {
name = "root-activity-trail"
s3_bucket_name = aws_s3_bucket.cloudtrail_logs.bucket
include_global_service_events = true
is_multi_region_trail = true
enable_logging = true
}
resource "aws_s3_bucket" "cloudtrail_logs" {
bucket = "CLOUDTRAIL_LOG_BUCKET_NAME" # replace with a globally-unique bucket name
}
resource "aws_cloudwatch_log_group" "cloudtrail" {
name = "/aws/cloudtrail/root-activity"
retention_in_days = 90
}
resource "aws_cloudtrail" "root_activity_trail_logs" {
depends_on = [aws_cloudwatch_log_group.cloudtrail]
name = "root-activity-trail-with-logs"
s3_bucket_name = aws_s3_bucket.cloudtrail_logs.bucket
include_global_service_events = true
is_multi_region_trail = true
enable_logging = true
cloud_watch_logs_group_arn = "${aws_cloudwatch_log_group.cloudtrail.arn}:*"
cloud_watch_logs_role_arn = aws_iam_role.cloudtrail_to_cw.arn
}
resource "aws_iam_role" "cloudtrail_to_cw" {
name = "cloudtrail-to-cloudwatch-role"
assume_role_policy = data.aws_iam_policy_document.cloudtrail_assume.json
}
data "aws_iam_policy_document" "cloudtrail_assume" {
statement {
effect = "Allow"
principals {
type = "Service"
identifiers = ["cloudtrail.amazonaws.com"]
}
actions = ["sts:AssumeRole"]
}
}
resource "aws_iam_role_policy" "cloudtrail_to_cw" {
role = aws_iam_role.cloudtrail_to_cw.id
policy = data.aws_iam_policy_document.cloudtrail_to_cw.json
}
data "aws_iam_policy_document" "cloudtrail_to_cw" {
statement {
effect = "Allow"
actions = [
"logs:CreateLogStream",
"logs:PutLogEvents",
]
resources = ["${aws_cloudwatch_log_group.cloudtrail.arn}:*"]
}
}
resource "aws_cloudwatch_log_metric_filter" "root_activity" {
name = "RootAccountActivity"
log_group_name = aws_cloudwatch_log_group.cloudtrail.name
pattern = "{ ($.userIdentity.type = \"Root\") && ($.userIdentity.invokedBy NOT EXISTS) && ($.eventType != \"AwsServiceEvent\") }"
metric_transformation {
name = "RootAccountActivity"
namespace = "CloudTrailMetrics"
value = "1"
}
}
resource "aws_sns_topic" "root_activity_alerts" {
name = "root-account-activity-alerts"
}
resource "aws_cloudwatch_metric_alarm" "root_activity" {
alarm_name = "RootAccountActivityAlarm"
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = 1
metric_name = aws_cloudwatch_log_metric_filter.root_activity.metric_transformation[0].name
namespace = aws_cloudwatch_log_metric_filter.root_activity.metric_transformation[0].namespace
period = 300
statistic = "Sum"
threshold = 1
alarm_actions = [aws_sns_topic.root_activity_alerts.arn]
}
This specific finding cannot be implemented on aws_iam_user because the root account has no Terraform resource; instead, monitoring must be done via CloudTrail and CloudWatch as shown, or by following the equivalent steps in the AWS Console.
For verification, terraform plan should show creation (or update) of the CloudTrail trail, CloudWatch log group, metric filter, SNS topic, and CloudWatch alarm that detect and alert on events where userIdentity.type = "Root".