Skip to content

CloudWatch Logs Insights for security: useful queries for AWS investigations

Collected logs only help if you can query them quickly. This guide collects defensive queries for investigating activity in AWS.

Reading time
8 min
Published

Collecting logs is half the job. The other half is being able to ask them questions under pressure, with the incident still unfolding. CloudWatch Logs Insights queries log groups with its own query language, which helps a lot when CloudTrail is sent to CloudWatch Logs. In an investigation, filtering quickly by event, identity and source is the difference between understanding the incident and staying in the dark.

The idea here is to use Logs Insights for investigations in AWS. The walkthrough starts with the CloudTrail fields that answer the most questions, moves on to queries by activity pattern, which come up in almost every case, and ends at the point where a recurring query becomes an alert, always with an explanation of how to read the result. The intended use is authorized analysis of your own environment, focused on detection and response.

CloudTrail fields that matter

Every CloudTrail event carries fields that answer the basic questions of an investigation. The eventName field tells you which action happened, sourceIPAddress shows where it came from, userIdentity identifies who acted and awsRegion tells you in which Region. The errorCode field, in turn, appears on denied attempts. Cross-referencing these fields reveals patterns such as an identity acting from an unusual IP or a sequence of denied actions, which suggests permission enumeration.

Query: IAM actions with identity and IP, newest first
fields @timestamp, eventName, userIdentity.arn, sourceIPAddress| filter eventSource = "iam.amazonaws.com"| sort @timestamp desc| limit 50

Extracting and grouping with parse and stats

Besides filtering, Logs Insights aggregates. The stats command summarizes activity, and bin groups events by time window, which makes bursts visible. A sudden spike from a single IP or a single identity in a short window (the 5 minutes in the query below, for example) usually tells you more than a long list of scattered events.

Query: event volume per identity, in 5-minute windows
fields @timestamp, userIdentity.arn| stats count(*) as events by bin(5m), userIdentity.arn| sort events desc

Queries by activity pattern

Some queries show up in almost every investigation. A list of denied attempts helps detect enumeration and permission abuse. Grouping actions by source IP shows where the activity came from. And a filter on sensitive events, such as the creation of users and keys or policy changes, reveals persistence attempts.

Query: denied attempts grouped by identity
fields @timestamp, eventName, userIdentity.arn, errorCode| filter ispresent(errorCode)| stats count(*) as attempts by userIdentity.arn, errorCode| sort attempts desc

Signs of credential abuse and persistence

Some events deserve a query of their own, because they point to session abuse or to someone setting up persistent access. Examples are AssumeRole and GetSessionToken calls at unusual volume, access key creation and changes to a role's trust policy. Filtering by these event names and cross-referencing the result with the identity and source IP helps separate normal operations from suspicious activity.

Query: AssumeRole usage and credential creation
fields @timestamp, eventName, userIdentity.arn, sourceIPAddress| filter eventName in ["AssumeRole", "GetSessionToken", "CreateAccessKey"]| stats count(*) as calls by userIdentity.arn, eventName| sort calls desc
  • Filter sensitive IAM events (user, key and policy creation)
  • Group activity by sourceIPAddress to see where it comes from
  • List errorCode values to catch enumeration and abuse
  • Watch for AssumeRole and GetSessionToken at unusual volume
  • Look for root account usage and services being turned off
  • Narrow the time window to the incident period

From query to alert

Investigating after the fact is useful, but ideally some patterns should raise the alarm on their own. With CloudTrail in CloudWatch Logs, you create a metric filter that counts the occurrences of a pattern and attach that filter to an alarm. From then on, events such as root account usage or CloudTrail being stopped send a notification by themselves, without waiting for someone to run a query.

Metric filter pattern: root account usage
{ $.userIdentity.type = "Root" &&  $.userIdentity.invokedBy NOT EXISTS &&  $.eventType != "AwsServiceEvent" }

Send the alarm to a channel that has an owner and a response deadline. An alarm that only lights up on a dashboard depends on someone looking at it. Keep Logs Insights for fast investigation, when you need to explore the data and rebuild the timeline, and hand known, recurring patterns over to metric filters.

Limitations and good practices

Logs Insights only sees what is in the log group. If CloudTrail is not being sent to CloudWatch, or if retention is short, the query will not find the event. Billing is based on the volume of data scanned, so narrowing the time window lowers the cost and speeds up the result. For very large volumes or long windows, a data lake with queries can come out cheaper. And keep reusable queries ready, so you do not have to improvise in the middle of an incident.

Practical checklist

  • Send CloudTrail to CloudWatch Logs if investigations need fast queries
  • Set log group retention to what investigations need
  • Keep a standard set of investigation queries
  • Use stats and bin to see bursts by identity and by IP
  • Filter sensitive IAM events
  • Track AssumeRole, GetSessionToken and key creation
  • List denied attempts to detect enumeration
  • Limit the time window to the incident, which makes the query faster and cheaper
  • Create metric filters with alarms for critical patterns
  • Look for root account usage and services being disabled
  • Consider a data lake for large volumes and long windows

Best practices

  • Have your queries ready before the incident
  • Cross-reference event, identity and source to find patterns
  • Group with stats and bin so bursts of activity stand out
  • Treat denied attempts as a possible sign of enumeration
  • Turn known patterns into metric filters with alarms
  • Keep retention at least as long as it takes you to discover an incident
  • Narrow the time window to keep query costs under control

Common mistakes

CloudTrail not in CloudWatch when you need to query
The quick query cannot find the events the investigation needs.
Short log group retention
By the time the incident is discovered, the relevant events have already expired.
Improvising queries during the incident
Time is lost and, under pressure, what matters can slip by.
Ignoring errorCode
Enumeration and permission abuse go by without anyone noticing.
Querying huge windows without focus
The query gets expensive and slow, and the analysis is no clearer for it.
Relying only on manual queries, with no metric filter
Critical patterns sit waiting for someone to look, when they could be raising alerts.

Authorship and review

Cesar Gargiulo

CEO and founder of GUARDIASEC. Technical and editorial lead for the content published in this library.

Published on . Found a technical error? Write to [email protected] and we will correct it and keep a record of the change.

Frequently asked questions

Do I need to send CloudTrail to CloudWatch to use Logs Insights?
Yes. Logs Insights queries CloudWatch log groups, so to search CloudTrail events there, you have to send them to CloudWatch Logs. For large volumes, an alternative is to query CloudTrail logs directly in a data lake. What you cannot do without is a fast query path defined before you need it.
Which CloudTrail fields are most useful in an investigation?
The main ones are eventName (which action happened), sourceIPAddress (the source), userIdentity (who acted), awsRegion (where) and errorCode, which appears on denied attempts. By cross-referencing these fields you rebuild the timeline and find patterns such as activity from an unusual IP or sequences of denied actions.
How do I turn a recurring query into an alert?
Logs Insights queries run on demand and do not trigger alerts by themselves. For continuous alerting, create a metric filter on the log group that counts occurrences of the pattern (root usage or CloudTrail being stopped, for example) and attach a CloudWatch alarm to it. The pattern then sends notifications automatically, and Logs Insights is left for exploratory investigation.
Do Logs Insights queries cost money?
Yes. Logs Insights charges for the amount of data scanned by each query. So narrowing the time window and filtering early in the query reduces both the cost and the response time. For very long windows or very large volumes, a data lake with queries usually comes out cheaper than scanning huge log groups over and over.
Does Logs Insights replace a SIEM?
No. Logs Insights is great for fast investigation inside CloudWatch, but a SIEM correlates varied sources, such as applications, network and endpoints, with more elaborate rules and alerts. Each one complements the other: Logs Insights handles quick queries in the AWS environment, and the SIEM gives a broader, correlated view.
How do I use Logs Insights responsibly?
Responsible use means analyzing your own environment, with authorization and a defensive focus (detection, investigation and response). The queries read logs you already collect and involve no exploitation of third-party systems. Day to day, standardize your queries, narrow the time windows and turn frequent patterns into alerts.

When to bring in specialist help

Organizing the collection, queries and alerts used in investigations is the focus of GUARDIASEC's Monitoring and Response service. There we define the detection use cases and investigation workflows, so they are ready when an incident happens.