[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71CPV2YXHTHRW42E2RE1WDB":3,"skill-same:01M71CPV2YXHTHRW42E2RE1WDB":91},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":64,"commitSha":65,"skillDirectory":66,"forksCount":14,"repositoryHtmlUrl":67,"repositoryHomepageUrl":6,"ownerHtmlUrl":68,"ownerBlogUrl":6,"ownerDescription":69,"updatedAt":70,"install":71,"resources":84},"01M71CPV2YXHTHRW42E2RE1WDB","trail-analyze",null,"Implementing AWS CloudTrail log analysis for security monitoring, threat detection, and forensic investigation using Athena, CloudWatch Logs Insights, and SIEM integration to identify unauthorized access, privilege escalation, and suspicious API activity.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fcloud\u002Ftrail\u002Fanalyze\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"trail analyze","trail","analyze","access","implementing","insights","de","log","cm","log analysis","suspicious","Bash","api","analysis","log-analysis","threat-detection","monitoring","logs","siem","cybersecurity","2026-11-10 10:12:30",false,"---\nname: trail-analyze\ndescription: Implementing AWS CloudTrail log analysis for security monitoring, threat detection, and forensic investigation using Athena, CloudWatch Logs Insights, and SIEM integration to identify unauthorized access, privilege escalation, and suspicious API activity.\ndomain: cybersecurity\nsubdomain: cloud-security\ntags:\n- cloud-security\n- aws\n- cloudtrail\n- log-analysis\n- threat-detection\n- forensics\nnist_csf:\n- PR.IR-01\n- ID.AM-08\n- GV.SC-06\n- DE.CM-01\nmodel: sonnet\nmaxTurns: 20\ntools: [Read, Bash, Glob, Grep]\nmitre_attack:\n- T1059\n- T1070\ncapec: []\n---\n\n# Implementing CloudTrail Log Analysis\n\n## When to Use\n\n- When building security monitoring pipelines for AWS API activity\n- When investigating security incidents to trace attacker actions across AWS services\n- When compliance requires audit logging of all administrative and data access operations\n- When creating detection rules for known attack patterns in AWS environments\n- When establishing baseline API behavior for anomaly detection\n\n**Do not use** for real-time threat detection (use GuardDuty which already analyzes CloudTrail), for application-level logging (use CloudWatch Application Logs), or for network traffic analysis (use VPC Flow Logs).\n\n## Prerequisites\n\n- CloudTrail enabled with management events and optionally data events across all accounts\n- S3 bucket configured as CloudTrail delivery channel with appropriate retention policies\n- Amazon Athena configured with CloudTrail log table for ad-hoc queries\n- CloudWatch Logs subscription for real-time analysis with Logs Insights\n- SIEM integration (Splunk, Elastic, or Security Lake) for production monitoring\n\n## Workflow\n\n### Step 1: Configure CloudTrail for Comprehensive Logging\n\nEnsure CloudTrail captures all relevant event types across the organization.\n\n```bash\n# Create an organization trail (captures all accounts)\naws cloudtrail create-trail \\\n  --name org-security-trail \\\n  --s3-bucket-name cloudtrail-logs-org-ACCOUNT \\\n  --is-organization-trail \\\n  --is-multi-region-trail \\\n  --include-global-service-events \\\n  --enable-log-file-validation \\\n  --kms-key-id alias\u002Fcloudtrail-key \\\n  --cloud-watch-logs-log-group-arn arn:aws:logs:us-east-1:ACCOUNT:log-group:cloudtrail-org:* \\\n  --cloud-watch-logs-role-arn arn:aws:iam::ACCOUNT:role\u002FCloudTrailCloudWatchRole\n\n# Start logging\naws cloudtrail start-logging --name org-security-trail\n\n# Enable data events for S3 and Lambda\naws cloudtrail put-event-selectors \\\n  --trail-name org-security-trail \\\n  --advanced-event-selectors '[\n    {\n      \"Name\": \"S3DataEvents\",\n      \"FieldSelectors\": [\n        {\"Field\": \"eventCategory\", \"Equals\": [\"Data\"]},\n        {\"Field\": \"resources.type\", \"Equals\": [\"AWS::S3::Object\"]}\n      ]\n    },\n    {\n      \"Name\": \"LambdaDataEvents\",\n      \"FieldSelectors\": [\n        {\"Field\": \"eventCategory\", \"Equals\": [\"Data\"]},\n        {\"Field\": \"resources.type\", \"Equals\": [\"AWS::Lambda::Function\"]}\n      ]\n    }\n  ]'\n\n# Verify trail configuration\naws cloudtrail describe-trails --trail-name-list org-security-trail\n```\n\n### Step 2: Set Up Athena for CloudTrail Query Analysis\n\nCreate an Athena table for querying CloudTrail logs with SQL.\n\n```sql\n-- Create CloudTrail Athena table\nCREATE EXTERNAL TABLE cloudtrail_logs (\n  eventVersion STRING,\n  userIdentity STRUCT\u003C\n    type:STRING, principalId:STRING, arn:STRING,\n    accountId:STRING, invokedBy:STRING,\n    accessKeyId:STRING, userName:STRING,\n    sessionContext:STRUCT\u003C\n      attributes:STRUCT\u003CmfaAuthenticated:STRING, creationDate:STRING>,\n      sessionIssuer:STRUCT\u003Ctype:STRING, principalId:STRING, arn:STRING, accountId:STRING, userName:STRING>\n    >\n  >,\n  eventTime STRING,\n  eventSource STRING,\n  eventName STRING,\n  awsRegion STRING,\n  sourceIPAddress STRING,\n  userAgent STRING,\n  errorCode STRING,\n  errorMessage STRING,\n  requestParameters STRING,\n  responseElements STRING,\n  additionalEventData STRING,\n  requestId STRING,\n  eventId STRING,\n  readOnly STRING,\n  resources ARRAY\u003CSTRUCT\u003Carn:STRING, accountId:STRING, type:STRING>>,\n  eventType STRING,\n  apiVersion STRING,\n  recipientAccountId STRING,\n  sharedEventId STRING,\n  vpcEndpointId STRING\n)\nPARTITIONED BY (region STRING, year STRING, month STRING, day STRING)\nROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'\nLOCATION 's3:\u002F\u002Fcloudtrail-logs-org-ACCOUNT\u002FAWSLogs\u002FORG_ID\u002F';\n\n-- Add partitions for recent data\nALTER TABLE cloudtrail_logs ADD\n  PARTITION (region='us-east-1', year='2026', month='02', day='23')\n  LOCATION 's3:\u002F\u002Fcloudtrail-logs-org-ACCOUNT\u002FAWSLogs\u002FORG_ID\u002FACCOUNT\u002FCloudTrail\u002Fus-east-1\u002F2026\u002F02\u002F23\u002F';\n```\n\n### Step 3: Run Security-Focused Athena Queries\n\nExecute queries to detect common attack patterns and suspicious activity.\n\n```sql\n-- Detect console logins without MFA\nSELECT eventtime, useridentity.username, sourceipaddress, useridentity.arn\nFROM cloudtrail_logs\nWHERE eventname = 'ConsoleLogin'\n  AND additionalEventData LIKE '%\"MFAUsed\":\"No\"%'\n  AND errorcode IS NULL\nORDER BY eventtime DESC;\n\n-- Find IAM privilege escalation attempts\nSELECT eventtime, useridentity.arn, eventname, errorcode, sourceipaddress\nFROM cloudtrail_logs\nWHERE eventname IN (\n  'CreatePolicyVersion', 'SetDefaultPolicyVersion', 'AttachUserPolicy',\n  'AttachRolePolicy', 'PutUserPolicy', 'PutRolePolicy',\n  'CreateAccessKey', 'CreateLoginProfile', 'UpdateLoginProfile',\n  'PassRole', 'AssumeRole'\n)\nORDER BY eventtime DESC\nLIMIT 100;\n\n-- Detect CloudTrail tampering\nSELECT eventtime, useridentity.arn, eventname, requestparameters, sourceipaddress\nFROM cloudtrail_logs\nWHERE eventname IN ('StopLogging', 'DeleteTrail', 'UpdateTrail', 'PutEventSelectors')\nORDER BY eventtime DESC;\n\n-- Find API calls from Tor exit nodes or unusual IPs\nSELECT eventtime, useridentity.arn, eventname, sourceipaddress, awsregion\nFROM cloudtrail_logs\nWHERE sourceipaddress NOT LIKE '10.%'\n  AND sourceipaddress NOT LIKE '172.%'\n  AND sourceipaddress NOT LIKE '192.168.%'\n  AND useridentity.type = 'IAMUser'\n  AND errorcode IS NULL\nGROUP BY eventtime, useridentity.arn, eventname, sourceipaddress, awsregion\nORDER BY eventtime DESC\nLIMIT 200;\n\n-- Detect unauthorized API calls (AccessDenied patterns)\nSELECT useridentity.arn, eventname, COUNT(*) as denied_count\nFROM cloudtrail_logs\nWHERE errorcode IN ('AccessDenied', 'UnauthorizedAccess', 'Client.UnauthorizedAccess')\n  AND eventtime > date_format(date_add('day', -7, now()), '%Y-%m-%dT%H:%i:%sZ')\nGROUP BY useridentity.arn, eventname\nHAVING COUNT(*) > 10\nORDER BY denied_count DESC;\n```\n\n### Step 4: Build Real-Time Detection with CloudWatch Logs Insights\n\nCreate real-time queries for active security monitoring.\n\n```bash\n# Detect root account usage\naws logs start-query \\\n  --log-group-name cloudtrail-org \\\n  --start-time $(date -d \"24 hours ago\" +%s) \\\n  --end-time $(date +%s) \\\n  --query-string '\n    fields @timestamp, eventName, sourceIPAddress, userAgent\n    | filter userIdentity.type = \"Root\"\n    | sort @timestamp desc\n  '\n\n# Detect security group changes\naws logs start-query \\\n  --log-group-name cloudtrail-org \\\n  --start-time $(date -d \"24 hours ago\" +%s) \\\n  --end-time $(date +%s) \\\n  --query-string '\n    fields @timestamp, userIdentity.arn, eventName, requestParameters.groupId, sourceIPAddress\n    | filter eventName in [\"AuthorizeSecurityGroupIngress\", \"AuthorizeSecurityGroupEgress\", \"RevokeSecurityGroupIngress\", \"CreateSecurityGroup\"]\n    | sort @timestamp desc\n  '\n\n# Detect new IAM users or access keys created\naws logs start-query \\\n  --log-group-name cloudtrail-org \\\n  --start-time $(date -d \"24 hours ago\" +%s) \\\n  --end-time $(date +%s) \\\n  --query-string '\n    fields @timestamp, userIdentity.arn, eventName, requestParameters.userName, sourceIPAddress\n    | filter eventName in [\"CreateUser\", \"CreateAccessKey\", \"CreateLoginProfile\"]\n    | sort @timestamp desc\n  '\n```\n\n### Step 5: Create CloudWatch Metric Filters and Alarms\n\nSet up automated alerting for critical security events based on CIS Benchmark recommendations.\n\n```bash\n# CIS 3.1: Unauthorized API calls alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name unauthorized-api-calls \\\n  --filter-pattern '{($.errorCode = \"*UnauthorizedAccess\") || ($.errorCode = \"AccessDenied*\")}' \\\n  --metric-transformations '[{\"metricName\":\"UnauthorizedAPICalls\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n\naws cloudwatch put-metric-alarm \\\n  --alarm-name cis-unauthorized-api-calls \\\n  --metric-name UnauthorizedAPICalls --namespace CISBenchmark \\\n  --statistic Sum --period 300 --threshold 10 \\\n  --comparison-operator GreaterThanThreshold --evaluation-periods 1 \\\n  --alarm-actions arn:aws:sns:us-east-1:ACCOUNT:security-alerts\n\n# CIS 3.3: Root account usage alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name root-account-usage \\\n  --filter-pattern '{$.userIdentity.type = \"Root\" && $.userIdentity.invokedBy NOT EXISTS && $.eventType != \"AwsServiceEvent\"}' \\\n  --metric-transformations '[{\"metricName\":\"RootAccountUsage\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n\n# CIS 3.4: IAM policy changes alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name iam-policy-changes \\\n  --filter-pattern '{($.eventName=CreatePolicy) || ($.eventName=DeletePolicy) || ($.eventName=AttachRolePolicy) || ($.eventName=DetachRolePolicy) || ($.eventName=AttachUserPolicy) || ($.eventName=DetachUserPolicy)}' \\\n  --metric-transformations '[{\"metricName\":\"IAMPolicyChanges\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n\n# CIS 3.5: CloudTrail configuration changes alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name cloudtrail-changes \\\n  --filter-pattern '{($.eventName = StopLogging) || ($.eventName = DeleteTrail) || ($.eventName = UpdateTrail)}' \\\n  --metric-transformations '[{\"metricName\":\"CloudTrailChanges\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| CloudTrail | AWS service that records API calls made to AWS services, providing an audit trail of actions taken by users, roles, and services |\n| Management Events | CloudTrail events for control plane operations like creating resources, modifying IAM, and configuring services |\n| Data Events | CloudTrail events for data plane operations like S3 object access and Lambda function invocations, providing granular activity logging |\n| Log File Validation | CloudTrail feature that creates a digest file for verifying that log files have not been tampered with after delivery |\n| CloudTrail Lake | Managed data lake for CloudTrail events enabling SQL-based queries without managing Athena tables or S3 data |\n| Organization Trail | Single trail that captures API activity across all accounts in an AWS Organization to a central S3 bucket |\n\n## Tools & Systems\n\n- **Amazon Athena**: Serverless SQL query engine for analyzing CloudTrail logs stored in S3 at scale\n- **CloudWatch Logs Insights**: Real-time log query service for interactive CloudTrail analysis within the last 30 days\n- **CloudTrail Lake**: Managed event data lake with built-in SQL query capabilities and 7-year retention\n- **Amazon Security Lake**: Centralized security data lake that normalizes CloudTrail data into OCSF format for SIEM consumption\n- **AWS CloudTrail**: Core audit logging service capturing all API activity across AWS accounts and services\n\n## Common Scenarios\n\n### Scenario: Investigating an IAM Credential Compromise Through CloudTrail\n\n**Context**: GuardDuty alerts on `UnauthorizedAccess:IAMUser\u002FMaliciousIPCaller` for a developer's access key. The security team needs to trace all actions taken by the compromised credential.\n\n**Approach**:\n1. Query CloudTrail for all events by the compromised AccessKeyId across all regions\n2. Build a timeline of API calls to understand the attack sequence\n3. Identify the initial access point (when did the key first appear from a malicious IP)\n4. Map all resources created, modified, or accessed by the attacker\n5. Check for persistence mechanisms (new users, access keys, Lambda functions, EC2 instances)\n6. Verify CloudTrail was not tampered with (check for StopLogging or UpdateTrail events)\n7. Document the full attack chain and scope of impact for the incident response report\n\n**Pitfalls**: CloudTrail events can take up to 15 minutes to appear in S3 and CloudWatch Logs. For real-time visibility during active incidents, use CloudTrail Lake or CloudWatch Logs Insights rather than Athena queries against S3. Cross-region attacks require querying multiple region partitions in Athena.\n\n## Output Format\n\n```\nCloudTrail Security Analysis Report\n======================================\nAccount: 123456789012\nAnalysis Period: 2026-02-16 to 2026-02-23\nTrail: org-security-trail (organization-wide)\n\nSECURITY EVENTS DETECTED:\n  Root account logins:                  2\n  Console logins without MFA:           7\n  Privilege escalation attempts:       12\n  CloudTrail configuration changes:     0\n  Security group modifications:        34\n  Unauthorized API calls:             156\n\nHIGH-PRIORITY FINDINGS:\n[CT-001] Console Login Without MFA\n  User: admin-user\n  Time: 2026-02-22T14:30:00Z\n  IP: 203.0.113.50\n  Action Required: Enforce MFA via IAM policy\n\n[CT-002] IAM Privilege Escalation\n  User: dev-user\n  Time: 2026-02-23T03:15:00Z\n  Events: CreatePolicyVersion -> AttachRolePolicy\n  IP: 185.x.x.x (suspicious)\n  Action Required: Investigate credential compromise\n\nALERTING STATUS:\n  CIS metric filters configured: 14 \u002F 14\n  CloudWatch alarms active: 14 \u002F 14\n  Alerts fired (last 7 days): 8\n```\n","# Implementing CloudTrail Log Analysis\n\n## When to Use\n\n- When building security monitoring pipelines for AWS API activity\n- When investigating security incidents to trace attacker actions across AWS services\n- When compliance requires audit logging of all administrative and data access operations\n- When creating detection rules for known attack patterns in AWS environments\n- When establishing baseline API behavior for anomaly detection\n\n**Do not use** for real-time threat detection (use GuardDuty which already analyzes CloudTrail), for application-level logging (use CloudWatch Application Logs), or for network traffic analysis (use VPC Flow Logs).\n\n## Prerequisites\n\n- CloudTrail enabled with management events and optionally data events across all accounts\n- S3 bucket configured as CloudTrail delivery channel with appropriate retention policies\n- Amazon Athena configured with CloudTrail log table for ad-hoc queries\n- CloudWatch Logs subscription for real-time analysis with Logs Insights\n- SIEM integration (Splunk, Elastic, or Security Lake) for production monitoring\n\n## Workflow\n\n### Step 1: Configure CloudTrail for Comprehensive Logging\n\nEnsure CloudTrail captures all relevant event types across the organization.\n\n```bash\n# Create an organization trail (captures all accounts)\naws cloudtrail create-trail \\\n  --name org-security-trail \\\n  --s3-bucket-name cloudtrail-logs-org-ACCOUNT \\\n  --is-organization-trail \\\n  --is-multi-region-trail \\\n  --include-global-service-events \\\n  --enable-log-file-validation \\\n  --kms-key-id alias\u002Fcloudtrail-key \\\n  --cloud-watch-logs-log-group-arn arn:aws:logs:us-east-1:ACCOUNT:log-group:cloudtrail-org:* \\\n  --cloud-watch-logs-role-arn arn:aws:iam::ACCOUNT:role\u002FCloudTrailCloudWatchRole\n\n# Start logging\naws cloudtrail start-logging --name org-security-trail\n\n# Enable data events for S3 and Lambda\naws cloudtrail put-event-selectors \\\n  --trail-name org-security-trail \\\n  --advanced-event-selectors '[\n    {\n      \"Name\": \"S3DataEvents\",\n      \"FieldSelectors\": [\n        {\"Field\": \"eventCategory\", \"Equals\": [\"Data\"]},\n        {\"Field\": \"resources.type\", \"Equals\": [\"AWS::S3::Object\"]}\n      ]\n    },\n    {\n      \"Name\": \"LambdaDataEvents\",\n      \"FieldSelectors\": [\n        {\"Field\": \"eventCategory\", \"Equals\": [\"Data\"]},\n        {\"Field\": \"resources.type\", \"Equals\": [\"AWS::Lambda::Function\"]}\n      ]\n    }\n  ]'\n\n# Verify trail configuration\naws cloudtrail describe-trails --trail-name-list org-security-trail\n```\n\n### Step 2: Set Up Athena for CloudTrail Query Analysis\n\nCreate an Athena table for querying CloudTrail logs with SQL.\n\n```sql\n-- Create CloudTrail Athena table\nCREATE EXTERNAL TABLE cloudtrail_logs (\n  eventVersion STRING,\n  userIdentity STRUCT\u003C\n    type:STRING, principalId:STRING, arn:STRING,\n    accountId:STRING, invokedBy:STRING,\n    accessKeyId:STRING, userName:STRING,\n    sessionContext:STRUCT\u003C\n      attributes:STRUCT\u003CmfaAuthenticated:STRING, creationDate:STRING>,\n      sessionIssuer:STRUCT\u003Ctype:STRING, principalId:STRING, arn:STRING, accountId:STRING, userName:STRING>\n    >\n  >,\n  eventTime STRING,\n  eventSource STRING,\n  eventName STRING,\n  awsRegion STRING,\n  sourceIPAddress STRING,\n  userAgent STRING,\n  errorCode STRING,\n  errorMessage STRING,\n  requestParameters STRING,\n  responseElements STRING,\n  additionalEventData STRING,\n  requestId STRING,\n  eventId STRING,\n  readOnly STRING,\n  resources ARRAY\u003CSTRUCT\u003Carn:STRING, accountId:STRING, type:STRING>>,\n  eventType STRING,\n  apiVersion STRING,\n  recipientAccountId STRING,\n  sharedEventId STRING,\n  vpcEndpointId STRING\n)\nPARTITIONED BY (region STRING, year STRING, month STRING, day STRING)\nROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'\nLOCATION 's3:\u002F\u002Fcloudtrail-logs-org-ACCOUNT\u002FAWSLogs\u002FORG_ID\u002F';\n\n-- Add partitions for recent data\nALTER TABLE cloudtrail_logs ADD\n  PARTITION (region='us-east-1', year='2026', month='02', day='23')\n  LOCATION 's3:\u002F\u002Fcloudtrail-logs-org-ACCOUNT\u002FAWSLogs\u002FORG_ID\u002FACCOUNT\u002FCloudTrail\u002Fus-east-1\u002F2026\u002F02\u002F23\u002F';\n```\n\n### Step 3: Run Security-Focused Athena Queries\n\nExecute queries to detect common attack patterns and suspicious activity.\n\n```sql\n-- Detect console logins without MFA\nSELECT eventtime, useridentity.username, sourceipaddress, useridentity.arn\nFROM cloudtrail_logs\nWHERE eventname = 'ConsoleLogin'\n  AND additionalEventData LIKE '%\"MFAUsed\":\"No\"%'\n  AND errorcode IS NULL\nORDER BY eventtime DESC;\n\n-- Find IAM privilege escalation attempts\nSELECT eventtime, useridentity.arn, eventname, errorcode, sourceipaddress\nFROM cloudtrail_logs\nWHERE eventname IN (\n  'CreatePolicyVersion', 'SetDefaultPolicyVersion', 'AttachUserPolicy',\n  'AttachRolePolicy', 'PutUserPolicy', 'PutRolePolicy',\n  'CreateAccessKey', 'CreateLoginProfile', 'UpdateLoginProfile',\n  'PassRole', 'AssumeRole'\n)\nORDER BY eventtime DESC\nLIMIT 100;\n\n-- Detect CloudTrail tampering\nSELECT eventtime, useridentity.arn, eventname, requestparameters, sourceipaddress\nFROM cloudtrail_logs\nWHERE eventname IN ('StopLogging', 'DeleteTrail', 'UpdateTrail', 'PutEventSelectors')\nORDER BY eventtime DESC;\n\n-- Find API calls from Tor exit nodes or unusual IPs\nSELECT eventtime, useridentity.arn, eventname, sourceipaddress, awsregion\nFROM cloudtrail_logs\nWHERE sourceipaddress NOT LIKE '10.%'\n  AND sourceipaddress NOT LIKE '172.%'\n  AND sourceipaddress NOT LIKE '192.168.%'\n  AND useridentity.type = 'IAMUser'\n  AND errorcode IS NULL\nGROUP BY eventtime, useridentity.arn, eventname, sourceipaddress, awsregion\nORDER BY eventtime DESC\nLIMIT 200;\n\n-- Detect unauthorized API calls (AccessDenied patterns)\nSELECT useridentity.arn, eventname, COUNT(*) as denied_count\nFROM cloudtrail_logs\nWHERE errorcode IN ('AccessDenied', 'UnauthorizedAccess', 'Client.UnauthorizedAccess')\n  AND eventtime > date_format(date_add('day', -7, now()), '%Y-%m-%dT%H:%i:%sZ')\nGROUP BY useridentity.arn, eventname\nHAVING COUNT(*) > 10\nORDER BY denied_count DESC;\n```\n\n### Step 4: Build Real-Time Detection with CloudWatch Logs Insights\n\nCreate real-time queries for active security monitoring.\n\n```bash\n# Detect root account usage\naws logs start-query \\\n  --log-group-name cloudtrail-org \\\n  --start-time $(date -d \"24 hours ago\" +%s) \\\n  --end-time $(date +%s) \\\n  --query-string '\n    fields @timestamp, eventName, sourceIPAddress, userAgent\n    | filter userIdentity.type = \"Root\"\n    | sort @timestamp desc\n  '\n\n# Detect security group changes\naws logs start-query \\\n  --log-group-name cloudtrail-org \\\n  --start-time $(date -d \"24 hours ago\" +%s) \\\n  --end-time $(date +%s) \\\n  --query-string '\n    fields @timestamp, userIdentity.arn, eventName, requestParameters.groupId, sourceIPAddress\n    | filter eventName in [\"AuthorizeSecurityGroupIngress\", \"AuthorizeSecurityGroupEgress\", \"RevokeSecurityGroupIngress\", \"CreateSecurityGroup\"]\n    | sort @timestamp desc\n  '\n\n# Detect new IAM users or access keys created\naws logs start-query \\\n  --log-group-name cloudtrail-org \\\n  --start-time $(date -d \"24 hours ago\" +%s) \\\n  --end-time $(date +%s) \\\n  --query-string '\n    fields @timestamp, userIdentity.arn, eventName, requestParameters.userName, sourceIPAddress\n    | filter eventName in [\"CreateUser\", \"CreateAccessKey\", \"CreateLoginProfile\"]\n    | sort @timestamp desc\n  '\n```\n\n### Step 5: Create CloudWatch Metric Filters and Alarms\n\nSet up automated alerting for critical security events based on CIS Benchmark recommendations.\n\n```bash\n# CIS 3.1: Unauthorized API calls alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name unauthorized-api-calls \\\n  --filter-pattern '{($.errorCode = \"*UnauthorizedAccess\") || ($.errorCode = \"AccessDenied*\")}' \\\n  --metric-transformations '[{\"metricName\":\"UnauthorizedAPICalls\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n\naws cloudwatch put-metric-alarm \\\n  --alarm-name cis-unauthorized-api-calls \\\n  --metric-name UnauthorizedAPICalls --namespace CISBenchmark \\\n  --statistic Sum --period 300 --threshold 10 \\\n  --comparison-operator GreaterThanThreshold --evaluation-periods 1 \\\n  --alarm-actions arn:aws:sns:us-east-1:ACCOUNT:security-alerts\n\n# CIS 3.3: Root account usage alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name root-account-usage \\\n  --filter-pattern '{$.userIdentity.type = \"Root\" && $.userIdentity.invokedBy NOT EXISTS && $.eventType != \"AwsServiceEvent\"}' \\\n  --metric-transformations '[{\"metricName\":\"RootAccountUsage\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n\n# CIS 3.4: IAM policy changes alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name iam-policy-changes \\\n  --filter-pattern '{($.eventName=CreatePolicy) || ($.eventName=DeletePolicy) || ($.eventName=AttachRolePolicy) || ($.eventName=DetachRolePolicy) || ($.eventName=AttachUserPolicy) || ($.eventName=DetachUserPolicy)}' \\\n  --metric-transformations '[{\"metricName\":\"IAMPolicyChanges\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n\n# CIS 3.5: CloudTrail configuration changes alarm\naws logs put-metric-filter \\\n  --log-group-name cloudtrail-org \\\n  --filter-name cloudtrail-changes \\\n  --filter-pattern '{($.eventName = StopLogging) || ($.eventName = DeleteTrail) || ($.eventName = UpdateTrail)}' \\\n  --metric-transformations '[{\"metricName\":\"CloudTrailChanges\",\"metricNamespace\":\"CISBenchmark\",\"metricValue\":\"1\"}]'\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| CloudTrail | AWS service that records API calls made to AWS services, providing an audit trail of actions taken by users, roles, and services |\n| Management Events | CloudTrail events for control plane operations like creating resources, modifying IAM, and configuring services |\n| Data Events | CloudTrail events for data plane operations like S3 object access and Lambda function invocations, providing granular activity logging |\n| Log File Validation | CloudTrail feature that creates a digest file for verifying that log files have not been tampered with after delivery |\n| CloudTrail Lake | Managed data lake for CloudTrail events enabling SQL-based queries without managing Athena tables or S3 data |\n| Organization Trail | Single trail that captures API activity across all accounts in an AWS Organization to a central S3 bucket |\n\n## Tools & Systems\n\n- **Amazon Athena**: Serverless SQL query engine for analyzing CloudTrail logs stored in S3 at scale\n- **CloudWatch Logs Insights**: Real-time log query service for interactive CloudTrail analysis within the last 30 days\n- **CloudTrail Lake**: Managed event data lake with built-in SQL query capabilities and 7-year retention\n- **Amazon Security Lake**: Centralized security data lake that normalizes CloudTrail data into OCSF format for SIEM consumption\n- **AWS CloudTrail**: Core audit logging service capturing all API activity across AWS accounts and services\n\n## Common Scenarios\n\n### Scenario: Investigating an IAM Credential Compromise Through CloudTrail\n\n**Context**: GuardDuty alerts on `UnauthorizedAccess:IAMUser\u002FMaliciousIPCaller` for a developer's access key. The security team needs to trace all actions taken by the compromised credential.\n\n**Approach**:\n1. Query CloudTrail for all events by the compromised AccessKeyId across all regions\n2. Build a timeline of API calls to understand the attack sequence\n3. Identify the initial access point (when did the key first appear from a malicious IP)\n4. Map all resources created, modified, or accessed by the attacker\n5. Check for persistence mechanisms (new users, access keys, Lambda functions, EC2 instances)\n6. Verify CloudTrail was not tampered with (check for StopLogging or UpdateTrail events)\n7. Document the full attack chain and scope of impact for the incident response report\n\n**Pitfalls**: CloudTrail events can take up to 15 minutes to appear in S3 and CloudWatch Logs. For real-time visibility during active incidents, use CloudTrail Lake or CloudWatch Logs Insights rather than Athena queries against S3. Cross-region attacks require querying multiple region partitions in Athena.\n\n## Output Format\n\n```\nCloudTrail Security Analysis Report\n======================================\nAccount: 123456789012\nAnalysis Period: 2026-02-16 to 2026-02-23\nTrail: org-security-trail (organization-wide)\n\nSECURITY EVENTS DETECTED:\n  Root account logins:                  2\n  Console logins without MFA:           7\n  Privilege escalation attempts:       12\n  CloudTrail configuration changes:     0\n  Security group modifications:        34\n  Unauthorized API calls:             156\n\nHIGH-PRIORITY FINDINGS:\n[CT-001] Console Login Without MFA\n  User: admin-user\n  Time: 2026-02-22T14:30:00Z\n  IP: 203.0.113.50\n  Action Required: Enforce MFA via IAM policy\n\n[CT-002] IAM Privilege Escalation\n  User: dev-user\n  Time: 2026-02-23T03:15:00Z\n  Events: CreatePolicyVersion -> AttachRolePolicy\n  IP: 185.x.x.x (suspicious)\n  Action Required: Investigate credential compromise\n\nALERTING STATUS:\n  CIS metric filters configured: 14 \u002F 14\n  CloudWatch alarms active: 14 \u002F 14\n  Alerts fired (last 7 days): 8\n```\n",{"name":5,"tags":44,"capec":49,"model":50,"tools":51,"domain":38,"maxTurns":55,"nist_csf":56,"subdomain":45,"description":7,"mitre_attack":61},[45,46,47,33,34,48],"cloud-security","aws","cloudtrail","forensics",[],"sonnet",[52,30,53,54],"Read","Glob","Grep",20,[57,58,59,60],"PR.IR-01","ID.AM-08","GV.SC-06","DE.CM-01",[62,63],"T1059","T1070","main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fcloud\u002Ftrail\u002Fanalyze","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":72,"prompt":82,"zipAvailable":83},[73,76,79],{"tool":74,"command":75},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill trail-analyze",{"tool":77,"command":78},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill trail-analyze",{"tool":80,"command":81},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill trail-analyze","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fcloud\u002Ftrail\u002Fanalyze\u002FSKILL.md",true,[85],{"path":86,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":89,"sourceHtmlUrl":90},"index.json","REFERENCE","参考文档",650,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fcloud\u002Ftrail\u002Fanalyze\u002Findex.json",[92,114,135,155,177,192],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":39},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[99,100,101,102,103,25,27,104,105,106,107,108,109,110,111,112,48,38,113],"services","detect","services wmi persistence detect","wmi","persistence","process","activescript","event","subscriptions","commandline-consumer","repository","subscription","event-subscription","t1546.003","process-forensics",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":39},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[121,99,122,102,123,124,125,38,30,32,126,127,128,129,25,130,131,132,133,134],"exploit","services wmi exec exploit","exec","remote","traffic","team","across","crackmapexec","native","command","lateral movement","read","lateral-movement","Impacket",{"skillNo":136,"name":137,"nameZh":6,"description":138,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":141,"publishedAt":39},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[142,143,144,145,146,147,38,30,148,32,21,149,25,132,150,151,152,153,154,50],"artifact","registry","registry artifact extract","extract","evidence-collection","artifact-analysis","collection","uncover","software","activity","digital-forensics","windows-registry","regripper",{"skillNo":156,"name":157,"nameZh":6,"description":158,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":159,"categories":160,"keywords":161,"publishedAt":39},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[100,162,163,164,165,166,167,27,168,38,113,169,170,171,172,173,174,175,176,25],"processes token impersonate detect","token","processes","attacks","windows","escalation","techniques","privilege-escalation","seimpersonate","token-impersonation","printspoofer","exploitation","potato","impersonation","via",{"skillNo":178,"name":179,"nameZh":6,"description":180,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":181,"categories":182,"keywords":183,"publishedAt":39},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[184,185,100,186,164,166,187,27,188,168,38,113,32,31,189,190,191,176,25,104],"thread","processes thread injection detect","injection","memory","process-injection","apc-injection","thread-injection","nt-api",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":198,"publishedAt":39},"01M71HA7H311V5G14WMX58HQSS","processes-hollow-technique-detect","Detect process hollowing (RunPE) by identifying processes with mismatched image paths between PEB and VAD tree, or unmapped PE headers in memory.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fhollow\u002Ftechnique\u002Fdetect\u002FSKILL.md",[],[199,100,164,200,187,27,201,202,38,113,203,204,205,206,207,208,25,104,209,210],"processes hollow technique detect","tree","memory-forensics","process-hollow","peb","runpe","image","pe-header","in memory","with","mismatched","headers"]