Sub topic 10
Alerting on sensitive API calls
This chapter shows how to turn CloudTrail records into notifications, so you learn about a risky change when it happens and not during a later review. It assumes you can read a CloudTrail event record, you have a trail running, and you can create an Amazon SNS topic and use the AWS CLI. The examples use account 123456789012 and Region us-east-1.
Two routes from an event to an alert
CloudTrail does not send notifications itself. You build alerting on one of two services that receive its events.
- Amazon EventBridge matches each event against a pattern and sends matches to a target such as an SNS topic, a Lambda function, or an SQS queue. It reacts to individual events and needs no trail for management events.
- Amazon CloudWatch Logs receives a copy of the trail's events in a log group. A metric filter counts matching log lines, and a CloudWatch alarm fires when the count crosses a threshold. This route needs a trail with CloudWatch Logs delivery configured.
| Aspect | EventBridge rule | CloudWatch Logs metric filter and alarm |
|---|---|---|
| Needs a trail | No for management events. Yes for data events. | Yes, with CloudWatch Logs delivery enabled |
| Granularity | One notification per matching event, with full event detail | A count over a period, such as "at least 1 in 5 minutes" |
| Good for | "Tell me every time X happens" | Thresholds, such as "more than 5 failed sign-ins in 10 minutes" |
| Scope | One Region per rule | One log group, which a multi-Region trail fills from all Regions |
| Extra cost | Little for the default bus | Log ingestion and storage, plus alarm charges |
Many teams use both. EventBridge handles rare, high-impact events. Metric filters handle patterns that only matter in volume.
Decide what is sensitive
Alerting on every API call produces noise, and people stop reading noisy alerts. Start with calls that are rare, high-impact, or that hide other activity:
- Changes to the audit trail itself:
StopLogging,DeleteTrail,UpdateTrail,PutEventSelectors. - Use of the root user.
- IAM changes that grant access:
CreateAccessKey,AttachUserPolicy,PutRolePolicy,CreateUser. - Console sign-in without multi-factor authentication, or repeated failed sign-ins.
- Network exposure changes, such as
AuthorizeSecurityGroupIngressorPutBucketPolicy. - Disabling or scheduling deletion of a KMS key:
DisableKey,ScheduleKeyDeletion.
The eventSource and eventName fields identify each call. These are the fields your patterns match on.
Route 1: EventBridge rule for trail tampering
Management events from CloudTrail arrive on the account's default event bus with the detail type AWS API Call via CloudTrail. The full CloudTrail record sits under the detail key, so the field names are the ones you already know, prefixed with detail.
First, create the SNS topic and subscribe an address:
aws sns create-topic --name security-alerts
aws sns subscribe \
--topic-arn arn:aws:sns:us-east-1:123456789012:security-alerts \
--protocol email \
--notification-endpoint [email protected]The subscription stays pending until the recipient clicks the confirmation link in the email.
Next, create the rule. The pattern matches four trail-changing calls on the CloudTrail service:
aws events put-rule \
--name cloudtrail-tamper \
--description "Alert when a CloudTrail trail is stopped or changed" \
--event-pattern '{
"source": ["aws.cloudtrail"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventSource": ["cloudtrail.amazonaws.com"],
"eventName": ["StopLogging", "DeleteTrail", "UpdateTrail", "PutEventSelectors"]
}
}'EventBridge cannot publish to the topic until the topic's access policy allows it. Save this as topic-policy.json:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowEventBridgePublish",
"Effect": "Allow",
"Principal": { "Service": "events.amazonaws.com" },
"Action": "sns:Publish",
"Resource": "arn:aws:sns:us-east-1:123456789012:security-alerts",
"Condition": {
"ArnEquals": {
"aws:SourceArn": "arn:aws:events:us-east-1:123456789012:rule/cloudtrail-tamper"
}
}
}
]
}Apply the policy and attach the topic as the rule's target. The input transformer replaces the raw JSON with a one-line message that a person can read on a phone:
aws sns set-topic-attributes \
--topic-arn arn:aws:sns:us-east-1:123456789012:security-alerts \
--attribute-name Policy \
--attribute-value file://topic-policy.json
aws events put-targets \
--rule cloudtrail-tamper \
--targets '[{
"Id": "notify-secops",
"Arn": "arn:aws:sns:us-east-1:123456789012:security-alerts",
"InputTransformer": {
"InputPathsMap": {
"who": "$.detail.userIdentity.arn",
"what": "$.detail.eventName",
"ip": "$.detail.sourceIPAddress",
"when": "$.detail.eventTime"
},
"InputTemplate": "\"CloudTrail change: <who> called <what> from <ip> at <when>\""
}
}]'A StopLogging call like the one in the sample record from earlier chapters now produces a message such as CloudTrail change: arn:aws:iam::123456789012:user/alice called StopLogging from 203.0.113.10 at 2026-11-20T09:15:42Z.
How pattern matching works
- Matching is exact and case-sensitive.
stopLoggingnever matchesStopLogging. - Each field takes a list, and any listed value matches. Different fields combine with AND.
- Patterns can also use prefix matching,
anything-but, andexistsoperators. For example,"errorCode": [{"exists": false}]limits a rule to calls that succeeded. - A pattern that names a field the event lacks matches nothing, and EventBridge gives no error.
You can test a pattern before relying on it. Use aws events test-event-pattern with a sample event, or call the sensitive API in a test account and check that the message arrives.
Route 2: metric filter for root user activity
Some conditions are better described as "this happened at least once in the last five minutes". For these, the trail must deliver to CloudWatch Logs. Update the trail with a log group and a role that CloudTrail assumes:
aws logs create-log-group --log-group-name CloudTrail/org-audit
aws cloudtrail update-trail \
--name org-audit-trail \
--cloud-watch-logs-log-group-arn arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail/org-audit:* \
--cloud-watch-logs-role-arn arn:aws:iam::123456789012:role/CloudTrailToCloudWatchLogsThe role must trust cloudtrail.amazonaws.com and allow logs:CreateLogStream and logs:PutLogEvents on that log group. Without these permissions the update succeeds, but no events reach the log group.
Then create a metric filter. This one counts root user activity, using the pattern from the CIS AWS Foundations Benchmark:
aws logs put-metric-filter \
--log-group-name CloudTrail/org-audit \
--filter-name RootUsage \
--filter-pattern '{ ($.userIdentity.type = "Root") && ($.userIdentity.invokedBy NOT EXISTS) && ($.eventType != "AwsServiceEvent") }' \
--metric-transformations metricName=RootUsageCount,metricNamespace=Security,metricValue=1The three conditions remove noise. The root user must be the actor. The call must not come from an AWS service acting on the root user's behalf (invokedBy). The event must not be a service-generated event.
Finally, create an alarm on the metric:
aws cloudwatch put-metric-alarm \
--alarm-name root-usage \
--metric-name RootUsageCount \
--namespace Security \
--statistic Sum \
--period 300 \
--evaluation-periods 1 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:123456789012:security-alerts--treat-missing-data notBreaching matters. The metric only receives data points when the filter matches, so most periods have no data. Without this setting the alarm can sit in INSUFFICIENT_DATA and never show a normal state.
Gotchas and failure modes
Regions and global services. EventBridge rules are regional. A rule in us-east-1 sees only events from that Region. Events from global services such as IAM are recorded in us-east-1, so IAM alerts belong there. For regional services, create the rule in every Region you use, or forward events to a central bus. A multi-Region trail delivering to one log group avoids this problem for the metric-filter route.
Data events need a trail. The default bus carries management events without a trail. S3 object-level events and other data events reach EventBridge only if a trail records them. Also check the selectors from the trails chapter, because an alert on DeleteObject never fires if no trail logs that call.
Delay. Alerts are not instant. The call, its CloudTrail record, and the delivery to your target each add time, normally minutes. The CloudWatch Logs route adds the alarm's evaluation period. Design for "learn within minutes", not "block in real time". To prevent an action, use IAM policies or service control policies.
Failed calls. A denied call still produces an event, with an errorCode such as AccessDenied. A burst of denied iam:* calls from one principal is often a better signal than the successes. Decide for each rule whether it should match successes, failures, or both.
Alerts that watch only themselves. If an attacker disables the trail, later events are not recorded, so you rely on the StopLogging event being recorded and delivered first. Protect the alerting path too. Restrict who can call events:DeleteRule, events:DisableRule, events:RemoveTargets, and sns:SetTopicAttributes, and consider a second alert on those calls.
Silent breakage. Alerts fail without any error: a subscription left unconfirmed, a missing topic policy, or a typo in an event name. Test each rule after creating it and again after infrastructure changes. Check the FailedInvocations metric of the rule in CloudWatch for delivery failures.
Loops. Do not make a rule's target perform an action that matches the same rule. A Lambda that calls UpdateTrail to repair a trail, triggered by UpdateTrail, will trigger itself repeatedly.
Exercise
You create an EventBridge rule for PutBucketPolicy that sends to an SNS topic. After you change a bucket policy, no email arrives. The rule's pattern is correct and the email subscription is confirmed. Name two other causes you should check.
Show answer
First, the SNS topic's access policy may not allow events.amazonaws.com to publish, so the rule's delivery fails. Check the rule's FailedInvocations metric. Second, the rule may be in a different Region from the API call. For example, you changed the policy through a regional endpoint in another Region, and the rule exists only in us-east-1. Other possible causes are that the rule has no target attached, or that the rule is disabled.
Exercise
A metric-filter alarm for failed console sign-ins stays in INSUFFICIENT_DATA for days, even though the filter and log delivery work. What setting fixes it, and why?
Show answer
Set --treat-missing-data notBreaching on the alarm. The filter only publishes a data point when a matching event occurs. Quiet periods have no data, and by default the alarm treats the missing data as insufficient and does not show an OK state. Treating missing data as not breaching makes those periods count as normal.