CloudTrail 與 GuardDuty
🔥 Vibe Prompt
"為所有帳戶設定 CloudTrail,建立組織追蹤。啟用 GuardDuty 並設定自動化回應。"
為什麼需要 CloudTrail 與 GuardDuty?
| 服務 | 功能 | 比喻 | |:----:|:----:|:----:| | CloudTrail | 記錄所有 AWS API 呼叫 | 監視器 — 記錄誰在什麼時候做了什麼 | | GuardDuty | 智慧威脅偵測 | 警衛 — 分析行為模式,發現異常 |
兩者相輔相成:CloudTrail 提供原始資料,GuardDuty 提供智慧分析。
CloudTrail 設定
resource "aws_cloudtrail" "org_trail" {
name = "org-trail"
s3_bucket_name = aws_s3_bucket.cloudtrail.id
include_global_service_events = true
is_multi_region_trail = true
enable_log_file_validation = true
is_organization_trail = true
event_selector {
read_write_type = "All"
include_management_events = true
}
}
resource "aws_s3_bucket" "cloudtrail" {
bucket = "myorg-cloudtrail-logs"
force_destroy = true
}
關鍵 CloudTrail 事件監控
| 事件 | 風險等級 | 說明 |
|:----:|:--------:|------|
| ConsoleLogin | 🔴 高 | 尤其注意 root 登入或無 MFA 登入 |
| CreateUser / CreateAccessKey | 🔴 高 | 異常的 IAM 建立行為 |
| PutRolePolicy | 🔴 高 | IAM 權限變更,可能是權限提升 |
| PutBucketAcl / PutBucketPolicy | 🟡 中 | S3 權限變更,可能導致資料外洩 |
| AuthorizeSecurityGroupIngress | 🟡 中 | 安全群組開放,可能暴露服務 |
| CreateNetworkAcl | 🟢 低 | 網路 ACL 變更 |
CloudTrail 最佳實踐
- ✅ 開啟組織追蹤:一次啟用,自動涵蓋所有帳戶
- ✅ 啟用日誌驗證:確保日誌未被竄改
- ✅ 啟用多區域追蹤:涵蓋所有 AWS 區域
- ✅ 日誌加密:使用 KMS 加密 S3 中的日誌
- ✅ 設定生命週期:30 天後移至 IA,1 年後移至 Glacier
# 使用 AWS CLI 查詢 CloudTrail 事件
# 找出所有 root 登入事件
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin \
--query 'Events[?UserIdentity.Type=="Root"]'
GuardDuty 威脅偵測
GuardDuty 使用機器學習和威脅情報來偵測異常行為。以下是它會告警的典型場景:
| 偵測類型 | 範例行為 | 嚴重程度 | |:--------:|---------|:--------:| | Backdoor | EC2 實例與已知惡意 IP 通訊 | 🔴 高 | | CryptoCurrency | EC2 連接到加密貨幣礦池 | 🔴 高 | | Recon | 來自陌生 IP 的大量 port scanning | 🟡 中 | | UnauthorizedAccess | IAM 使用者在異常時間/地點登入 | 🟡 中 | | Stealth | 關閉 CloudTrail 或 GuardDuty 本身 | 🔴 高 | | Discovery | 列出 S3 Bucket、IAM Role 等資源 | 🟢 低 |
自動化回應
resource "aws_cloudwatch_event_rule" "guardduty_finding" {
name = "guardduty-auto-response"
description = "Trigger on GuardDuty findings"
event_pattern = jsonencode({
source = ["aws.guardduty"]
detail-type = ["GuardDuty Finding"]
detail = {
severity = [4, 5, 6, 7, 8, 8.9, 9] # Medium to Critical
}
})
}
resource "aws_cloudwatch_event_target" "lambda_response" {
rule = aws_cloudwatch_event_rule.guardduty_finding.name
arn = aws_lambda_function.auto_response.arn
}
GuardDuty 成本估算
| 資料來源 | 百萬事件成本 | |:--------:|:-----------:| | CloudTrail 事件 | ~$4.00 | | VPC Flow Logs (1B) | ~$1.00 | | DNS 日誌 | ~$2.00 | | EKS 審計日誌 | ~$3.00 |
實戰:完整安全監控架構
AWS 帳戶
│
├── CloudTrail ──▶ S3 (加密) ──▶ Athena (查詢)
│ └── Glacier (封存)
│
├── GuardDuty ──▶ EventBridge ──▶ Lambda (自動回應)
│ ├── Slack 通知
│ ├── 隔離 EC2 (SG change)
│ └── 建立 Jira Ticket
│
└── Security Hub ──▶ 統一儀表板
├── GuardDuty 發現
├── Inspector 掃描
└── Config 合規檢查
關鍵要點
- ✅ CloudTrail = AWS 的 CCTV,記錄所有 API 呼叫
- ✅ GuardDuty = AI 警衛,自動分析異常行為
- ✅ 開啟組織追蹤 = 一次設定涵蓋所有帳戶
- ✅ GuardDuty 發現可透過 EventBridge 自動觸發回應
- ✅ Security Hub 統一顯示所有安全服務的發現
- ✅ 日誌加密與生命週期管理是不可忽略的成本控制
resource "aws_cloudtrail" "org_trail" {
name = "org-trail"
s3_bucket_name = aws_s3_bucket.cloudtrail.id
include_global_service_events = true
is_multi_region_trail = true
enable_log_file_validation = true
is_organization_trail = true
event_selector {
read_write_type = "All"
include_management_events = true
}
}
resource "aws_s3_bucket" "cloudtrail" {
bucket = "myorg-cloudtrail-logs"
}
resource "aws_s3_bucket_policy" "cloudtrail" {
bucket = aws_s3_bucket.cloudtrail.id
policy = jsonencode({
Statement = [{
Effect = "Allow"
Principal = { Service = "cloudtrail.amazonaws.com" }
Action = "s3:PutObject"
Resource = "${aws_s3_bucket.cloudtrail.arn}/AWSLogs/*"
Condition = {
StringEquals = { "s3:x-amz-acl" = "bucket-owner-full-control" }
}
}]
})
}
Key CloudTrail Events
# Console login (without MFA)
{ "eventName": "ConsoleLogin", "userIdentity": { ... }, "responseElements": { "ConsoleLogin": "Failure" } }
# Root activity
{ "userIdentity": { "type": "Root" }, "eventName": "..." }
# IAM policy change
{ "eventSource": "iam.amazonaws.com", "eventName": "PutRolePolicy" }
# S3 public access change
{ "eventSource": "s3.amazonaws.com", "eventName": "PutBucketAcl" }
GuardDuty
resource "aws_guardduty_detector" "main" {
enable = true
datasources {
s3_logs {
enable = true
}
kubernetes {
audit_logs {
enable = true
}
}
}
}
GuardDuty Finding Types
| Finding | Severity | What It Means | |---------|----------|---------------| | CryptoCurrency:EC2/BitcoinTool.B!DNS | High | EC2 mining crypto | | Backdoor:EC2/C&CActivity.B!DNS | High | Malware C&C | | UnauthorizedAccess:IAM/User.IAMUser | Medium | Suspicious IAM | | Policy:IAM/User/RootCredentialUsage | High | Root user activity | | Recon:EC2/PortProbeUnprotected | Low | Port scanning |
Automated Response
import boto3
def lambda_handler(event, context):
finding = event['detail']['finding']
finding_type = finding['type']
resource_arn = finding['resource']['arn']
severity = finding['severity']
if severity >= 7: # HIGH or CRITICAL
if 'EC2' in finding_type:
# Isolate the instance
ec2 = boto3.client('ec2')
instance_id = resource_arn.split('/')[-1]
ec2.modify_instance_attribute(
InstanceId=instance_id,
Groups=['sg-quarantine']
)
print(f"Isolated {instance_id} in quarantine SG")
elif 'IAM' in finding_type:
# Disable the key
iam = boto3.client('iam')
iam.update_access_key(
UserName=finding['resource']['accessKeyDetails']['userName'],
AccessKeyId=finding['resource']['accessKeyDetails']['accessKeyId'],
Status='Inactive'
)
print("Disabled compromised access key")
GuardDuty + Security Hub
GuardDuty → Security Hub → EventBridge → Lambda (auto-remediate)
↓
Slack notification
↓
PagerDuty (SEV-1/2)
Best Practices
- Enable CloudTrail in all regions
- Create organization trail (single log bucket)
- Enable log file validation (integrity)
- Enable GuardDuty in all accounts
- Set up automated response for critical findings
- Integrate with Security Hub for dashboard
監控與偵測:CloudTrail 與 GuardDuty
CloudTrail:誰做了什麼
CloudTrail 記錄 AWS 中的所有 API 呼叫——這是資安事件調查的第一步。當發生入侵時,CloudTrail Log 告訴你:攻擊者用了哪個 IAM User、從哪個 IP、呼叫了什麼 API。
GuardDuty:智慧威脅偵測
GuardDuty 使用機器學習來偵測異常行為——例如:
- EC2 執行個體突然對外連線到已知的惡意 IP
- IAM User 從異常的地理位置登入
- S3 Bucket 被公開存取
為什麼需要 CloudTrail + GuardDuty?
| 工具 | 用途 | 主動/被動 | |:----|:----|:---------| | CloudTrail | 記錄所有 API 呼叫(事後調查用) | 被動 | | GuardDuty | 即時偵測異常行為(主動告警) | 主動 |
下一章預告
這堂雲端安全課程從 IAM、CloudTrail、GuardDuty 到網路安全——你現在可以為 AWS 環境建立基本的安全防護。