<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: analyzing-cloudtrail-anomalies
description: >-
  Analyze AWS CloudTrail logs for anomalous activity patterns including unusual API calls,
  geographic anomalies, off-hours access, and indicators of compromise.
domain: cybersecurity
subdomain: cloud-security
tags:
  - aws
  - cloudtrail
  - anomaly-detection
  - threat-hunting
  - siem
  - athena
  - guardduty
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1078.004"]
---

# Analyzing CloudTrail Anomalies

## Overview

CloudTrail is the authoritative audit log for AWS API activity. This skill covers
systematic analysis of CloudTrail events to detect unauthorized access, credential
abuse, data exfiltration, and persistence mechanisms. It includes Athena queries,
CLI-based hunting, and anomaly detection patterns that map to MITRE ATT&CK techniques.

Mode: `[MODE: BLUE]` — Threat hunting and detection engineering.

## Prerequisites

- AWS CLI v2 with credentials
- IAM permissions: `cloudtrail:LookupEvents`, `athena:StartQueryExecution`,
  `s3:GetObject` (CloudTrail bucket), `guardduty:ListFindings`
- CloudTrail enabled in all regions with S3 delivery
- Athena table configured for CloudTrail logs (recommended)
- Python 3.10+ with `boto3`

## Key Concepts

### High-Value CloudTrail Events

Events that frequently indicate compromise or policy violation:

| Category | Events | ATT&CK |
|----------|--------|--------|
| Credential abuse | `GetSessionToken`, `AssumeRole`, `GetFederationToken` | T1550 |
| Persistence | `CreateUser`, `CreateAccessKey`, `CreateLoginProfile` | T1136 |
| Defense evasion | `StopLogging`, `DeleteTrail`, `UpdateTrail` | T1562.008 |
| Discovery | `DescribeInstances`, `ListBuckets`, `GetCallerIdentity` | T1580 |
| Exfiltration | `GetObject`, `CopySnapshot`, `ShareSnapshot` | T1537 |
| Privilege escalation | `CreatePolicyVersion`, `AttachRolePolicy`, `PutRolePolicy` | T1098 |

### Anomaly Detection Patterns

```bash
# 1. Console logins from new IP addresses
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin \
  --start-time "2026-03-01T00:00:00Z" | \
  jq '[.Events[].CloudTrailEvent | fromjson |
  {user: .userIdentity.arn, ip: .sourceIPAddress, time: .eventTime}]'

# 2. API calls from unusual regions
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=RunInstances \
  --start-time "2026-03-01T00:00:00Z" | \
  jq '[.Events[].CloudTrailEvent | fromjson |
  {region: .awsRegion, user: .userIdentity.arn, time: .eventTime}]'

# 3. Failed API calls (access denied = recon)
aws cloudtrail lookup-events \
  --start-time "2026-03-01T00:00:00Z" --max-results 100 | \
  jq '[.Events[].CloudTrailEvent | fromjson |
  select(.errorCode == "AccessDenied") |
  {event: .eventName, user: .userIdentity.arn, time: .eventTime}]'
```

### Athena Hunting Queries

```sql
-- Detect CloudTrail tampering
SELECT eventtime, useridentity.arn, eventsource, eventname, sourceipaddress
FROM cloudtrail_logs
WHERE eventname IN ('StopLogging', 'DeleteTrail', 'UpdateTrail', 'PutEventSelectors')
ORDER BY eventtime DESC;

-- Unusual cross-region activity
SELECT awsregion, COUNT(*) as event_count, useridentity.arn
FROM cloudtrail_logs
WHERE eventtime > date_add('day', -7, now())
GROUP BY awsregion, useridentity.arn
HAVING COUNT(*) > 100
ORDER BY event_count DESC;

-- Root account usage (should be near zero)
SELECT eventtime, eventname, sourceipaddress, useragent
FROM cloudtrail_logs
WHERE useridentity.type = 'Root'
AND eventtime > date_add('day', -30, now())
ORDER BY eventtime DESC;

-- Data exfiltration indicators
SELECT eventtime, useridentity.arn, eventname, requestparameters
FROM cloudtrail_logs
WHERE eventname IN ('GetObject', 'CopySnapshot', 'ModifySnapshotAttribute',
  'CreateSnapshot', 'ModifyImageAttribute', 'SharedSnapshotVolumeCreated')
AND eventtime > date_add('day', -7, now())
ORDER BY eventtime DESC LIMIT 200;
```

### GuardDuty Integration

```bash
# List high-severity GuardDuty findings
DETECTOR=$(aws guardduty list-detectors --query 'DetectorIds[0]' --output text)
aws guardduty list-findings --detector-id $DETECTOR \
  --finding-criteria '{"Criterion":{"severity":{"Gte":7}}}' | \
  jq '.FindingIds[]' | head -20 | while read fid; do
    aws guardduty get-findings --detector-id $DETECTOR --finding-ids "$fid"
  done
```

## Workflow

### Step 1: Verify CloudTrail Configuration

```bash
aws cloudtrail describe-trails | jq '.trailList[] | {
  Name, IsMultiRegionTrail, LogFileValidationEnabled,
  S3BucketName, IsOrganizationTrail, HasInsightSelectors}'
```

### Step 2: Run Anomaly Detection

```bash
node scripts/agent.js --days 7 --output /tmp/cloudtrail_anomalies.json
```

### Step 3: Correlate with GuardDuty

```bash
node scripts/agent.js --days 7 --guardduty --output /tmp/correlated_findings.json
```

### Step 4: Investigate Findings

Triage findings by severity and investigate high-confidence alerts with full event context.

## Detection

```yaml
title: Cloudtrail Anomalies Detection
id: b31bc535-5a1b-48c3-bbee-f3480b596104
status: experimental
description: Detects suspicious activity related to analyzing cloudtrail anomalies techniques in cloud security context
logsource:
  product: aws
  service: cloudtrail
detection:
  selection:
    eventName: "*Unauthorized*"
  condition: selection
level: medium
tags:
  - attack.t1078.004
  - attack.credential_access
falsepositives:
  - Automated cloud infrastructure provisioning by approved CI/CD pipelines
```

## Verification

- [ ] CloudTrail enabled in all regions with multi-region trail
- [ ] Log file validation enabled
- [ ] No `StopLogging` or `DeleteTrail` events detected
- [ ] Root account usage limited to break-glass scenarios
- [ ] All console logins originate from expected IP ranges
- [ ] No AccessDenied enumeration patterns detected
- [ ] GuardDuty enabled and high-severity findings triaged

## References

- [AWS CloudTrail User Guide](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/)
- [MITRE ATT&CK — Cloud Matrix](https://attack.mitre.org/matrices/enterprise/cloud/)
- [AWS Security Incident Response Guide](https://docs.aws.amazon.com/whitepapers/latest/aws-security-incident-response-guide/)
- [Athena CloudTrail Table Setup](https://docs.aws.amazon.com/athena/latest/ug/cloudtrail-logs.html)
