[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GY993G0VSMS4AP214ZSFQG":3,"skill-same:01M6GY993G0VSMS4AP214ZSFQG":88},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":6,"ownerHtmlUrl":55,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":56,"install":57,"resources":70},"01M6GY993G0VSMS4AP214ZSFQG","implementing-cloud-trail-log-analysis",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.","micsapp\u002Fmicstec-skills","micsapp","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F82411001?v=4","01M6GWCFQ6D3PV8EHNY62NN5VW","01M6GWCFVE1PA5HG0DKC7AMFJ3",4,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fimplementing-cloud-trail-log-analysis\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"implementing cloud trail log analysis","trail","log","log analysis","analysis","cloud","monitoring","cloud-security","threat-detection","log-analysis","suspicious","logs","api","access","siem","cybersecurity","activity","insights","privilege escalation","security","2026-11-10 10:12:30",false,"---\nname: implementing-cloud-trail-log-analysis\ndescription: >\n  Implementing AWS CloudTrail log analysis for security monitoring, threat detection, and\n  forensic investigation using Athena, CloudWatch Logs Insights, and SIEM integration to\n  identify unauthorized access, privilege escalation, and suspicious API activity.\ndomain: cybersecurity\nsubdomain: cloud-security\ntags: [cloud-security, aws, cloudtrail, log-analysis, threat-detection, forensics]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\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":43,"author":47,"domain":33,"license":14,"version":48,"subdomain":25,"description":49},[25,44,45,27,26,46],"aws","cloudtrail","forensics","mahipal","1.0","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.\n","master","3f5d983eb4ef375b749adcd6b07ec03bd82ae8a8","_universal\u002Fcybersecurity-skills\u002Fskills\u002Fimplementing-cloud-trail-log-analysis",0,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills","https:\u002F\u002Fgithub.com\u002Fmicsapp","2026-03-20 11:24:18",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add micsapp\u002Fmicstec-skills --skill implementing-cloud-trail-log-analysis",{"tool":63,"command":64},"bunx","bunx skills add micsapp\u002Fmicstec-skills --skill implementing-cloud-trail-log-analysis",{"tool":66,"command":67},"pnpm","pnpm dlx skills add micsapp\u002Fmicstec-skills --skill implementing-cloud-trail-log-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fimplementing-cloud-trail-log-analysis\u002FSKILL.md",true,[71,76,82],{"path":72,"resourceType":72,"resourceTypeDesc":73,"sizeBytes":74,"sourceHtmlUrl":75},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fimplementing-cloud-trail-log-analysis\u002FLICENSE",{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fapi-reference.md","REFERENCE","参考文档",2244,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fimplementing-cloud-trail-log-analysis\u002Freferences\u002Fapi-reference.md",{"path":83,"resourceType":84,"resourceTypeDesc":85,"sizeBytes":86,"sourceHtmlUrl":87},"scripts\u002Fagent.py","SCRIPT","脚本",7527,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fimplementing-cloud-trail-log-analysis\u002Fscripts\u002Fagent.py",[89,126,156,175,195,220],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":106,"publishedAt":38},"01M6HBTJ02FXBFG9NYEHHYAP52","azure-apim-architecture","Analyzes and explains Azure API Management architecture decisions for enterprise API marketplace implementations using VNet Internal mode, Front Door, hybrid authentication, and multi-environment strategies. Use when discussing APIM component selection, network topology, cost optimization, or comparing alternatives like workspaces vs instances, VNet Internal vs External mode, or Front Door vs Application Gateway.","MIT","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fazure-apim-architecture\u002FSKILL.md",[96,101],{"categoryNo":97,"categoryName":98,"taxonomyType":99,"taxonomyTypeDesc":100},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":102,"categoryName":103,"taxonomyType":104,"taxonomyTypeDesc":105},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[107,108,109,110,111,112,113,114,115,30,116,117,118,119,120,121,122,123,124,125],"architecture","azure","azure apim architecture","component","authentication","gateway","topology","Optimization","network","team","environment","multi-environment","workspaces","instances","selection","strategies","azure api management","mode","for",{"skillNo":127,"name":128,"nameZh":6,"description":129,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":130,"categories":131,"keywords":140,"publishedAt":38},"01M6HBT7J4H082JEEA670B3EQ9","apiops-deployment","Guides deployment of Azure API Management infrastructure using Infrastructure as Code (Bicep\u002FTerraform), CI\u002FCD pipelines (GitHub Actions\u002FAzure DevOps), and APIOps workflows. Use when deploying APIM, creating pipelines, or implementing dev→test→prod promotion strategies.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapiops-deployment\u002FSKILL.md",[132,133,136,139],{"categoryNo":97,"categoryName":98,"taxonomyType":99,"taxonomyTypeDesc":100},{"categoryNo":134,"categoryName":135,"taxonomyType":99,"taxonomyTypeDesc":100},"01JBSEEDCAT000000000000011","运维与部署",{"categoryNo":137,"categoryName":138,"taxonomyType":99,"taxonomyTypeDesc":100},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":102,"categoryName":103,"taxonomyType":104,"taxonomyTypeDesc":105},[141,142,143,144,108,145,146,147,148,149,150,151,30,116,122,152,153,123,154,155],"deployment","apiops deployment","workflows","azure devops","infrastructure","code","infrastructure as code","actions","ci","github actions","github-actions","as","guides","CI\u002FCD","implementing",{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":163,"publishedAt":38},"01M6HBT2HEA23THNE9E00GYQBE","apim-policy-authoring","Creates production-ready Azure API Management policy XML for authentication (OAuth 2.0, JWT validation, subscription keys), rate limiting, CORS configuration, error handling, and API transformations. Use when implementing API security, access control, or request\u002Fresponse processing logic.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapim-policy-authoring\u002FSKILL.md",[162],{"categoryNo":97,"categoryName":98,"taxonomyType":99,"taxonomyTypeDesc":100},[164,165,166,37,108,111,30,116,31,167,168,169,170,171,172,123,173,174,155,125],"policy","authoring","apim policy authoring","use","ready","api security","Access Control","error","processing","cors configuration","production-ready",{"skillNo":176,"name":177,"nameZh":6,"description":178,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":179,"categories":180,"keywords":183,"publishedAt":38},"01M6HBSY65SB29J9WE9KYD0K6T","api-security-review","Reviews Azure API Management configurations for security vulnerabilities, OWASP API Security Top 10 compliance, VNet Internal mode validation, Private Link verification, and Azure Security Benchmark alignment. Use when performing security audits, pre-deployment validation, or compliance reviews.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapi-security-review\u002FSKILL.md",[181,182],{"categoryNo":97,"categoryName":98,"taxonomyType":99,"taxonomyTypeDesc":100},{"categoryNo":102,"categoryName":103,"taxonomyType":104,"taxonomyTypeDesc":105},[184,37,185,30,169,186,108,141,187,188,189,190,116,191,123,192,193,194,124,125],"review","security review","api security review","benchmark","verification","owasp","owasp-api","alignment","azure security","reviews","top",{"skillNo":196,"name":197,"nameZh":6,"description":198,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":199,"categories":200,"keywords":201,"publishedAt":38},"01M6HBSRW4PDFE6K4F8JYPZQ05","jira-cli","Interact with Jira from the command line to create, list, view, edit, and transition issues, manage sprints and epics, and perform common Jira workflows. Use when the user asks about Jira tasks, tickets, issues, sprints, or needs to manage project work items.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fjira-cli\u002FSKILL.md",[],[202,203,204,143,205,206,207,208,30,209,210,211,212,213,214,215,216,217,218,219],"cli","jira","jira cli","init","tasks","create","issues","common","work","command","edit","list","view","project","project work","token","line","sprints",{"skillNo":221,"name":222,"nameZh":6,"description":223,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":224,"categories":225,"keywords":226,"publishedAt":38},"01M6HBSNS3JHMW603G47TWE31H","calculator","Performs arbitrary-precision arithmetic calculations including addition, subtraction, multiplication, division, and exponents. Use when the user asks to calculate, compute, or evaluate math expressions, or when precise decimal arithmetic is needed to avoid floating-point errors.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fcalculator\u002FSKILL.md",[],[222,227,228,229,230,231,232,167,233,234],"npm","js","calculate","node","math","user","compute","errors"]