higakikeita/tfdrift-falco

GitHub: higakikeita/tfdrift-falco

基于 Falco 的事件驱动 Terraform 漂移检测器,实时监控云审计日志并与 IaC 状态比对,即时告警手动变更并关联操作者身份。

Stars: 14 | Forks: 1

# 🛰️ TFDrift-Falco **由 Falco 驱动的实时 Terraform Drift 检测** [![Version](https://img.shields.io/badge/version-0.5.0-blue)](https://github.com/higakikeita/tfdrift-falco/releases) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Go Version](https://img.shields.io/badge/Go-1.21+-00ADD8?logo=go)](https://golang.org/) [![Falco](https://img.shields.io/badge/Falco-Compatible-blue)](https://falco.org/) [![Docker](https://img.shields.io/badge/Docker-GHCR-2496ED?logo=docker)](https://ghcr.io/higakikeita/tfdrift-falco) [![Docker Pulls](https://img.shields.io/badge/dynamic/json?url=https://ghcr.io/v2/higakikeita/tfdrift-falco/manifests/latest&label=pulls&query=$.name&color=2496ED&logo=docker)](https://github.com/higakikeita/tfdrift-falco/pkgs/container/tfdrift-falco) [![Test](https://github.com/higakikeita/tfdrift-falco/actions/workflows/test.yml/badge.svg)](https://github.com/higakikeita/tfdrift-falco/actions/workflows/test.yml) [![Lint](https://github.com/higakikeita/tfdrift-falco/actions/workflows/lint.yml/badge.svg)](https://github.com/higakikeita/tfdrift-falco/actions/workflows/lint.yml) [![Security](https://github.com/higakikeita/tfdrift-falco/actions/workflows/security.yml/badge.svg)](https://github.com/higakikeita/tfdrift-falco/actions/workflows/security.yml) [![Publish GHCR](https://static.pigsec.cn/wp-content/uploads/repos/2026/03/a6428016f5135757.svg)](https://github.com/higakikeita/tfdrift-falco/actions/workflows/publish-ghcr.yml) [![Coverage](https://img.shields.io/badge/coverage-85.0%25-brightgreen)](https://github.com/higakikeita/tfdrift-falco) [![codecov](https://codecov.io/gh/higakikeita/tfdrift-falco/branch/main/graph/badge.svg)](https://codecov.io/gh/higakikeita/tfdrift-falco) [![Go Report Card](https://goreportcard.com/badge/github.com/higakikeita/tfdrift-falco)](https://goreportcard.com/report/github.com/higakikeita/tfdrift-falco) **[English]** | [日本語 (Japanese)](README.ja.md) ## 🚀 快速开始 (3 条命令!) ### 最快设置 (5 分钟) ``` # 1. Clone repository git clone https://github.com/higakikeita/tfdrift-falco.git && cd tfdrift-falco # 2. 运行安装脚本 (交互式配置) ./quick-start.sh # 3. 启动! docker compose up -d ``` **就是这样!** 🎉 脚本会自动: - ✅ 检查 Docker / Docker Compose - ✅ 验证 AWS 凭证 - ✅ 生成 Falco + TFDrift-Falco 配置文件 - ✅ 交互式设置 (AWS Region, Terraform State Backend, Slack Webhook) ### 查看日志 ``` # 显示漂移检测日志 docker compose logs -f tfdrift # 或者使用 make 命令 make logs ``` ### 常用命令 ``` make start # Start services make stop # Stop services make restart # Restart services make status # Check status make logs # View logs ``` ### 详细设置指南 有关分步说明,请参阅 [入门指南](docs/GETTING_STARTED.md)。 ## ⚙️ 配置 TFDrift-Falco 需要您配置 AWS 账户和 Terraform state 位置。 ### 步骤 1:创建配置文件 ``` # 复制示例配置 cp config.yaml.example config.yaml ``` ### 步骤 2:替换占位符 编辑 `config.yaml` 并将 **`YOUR-AWS-ACCOUNT-ID`** 替换为您实际的 AWS 账户 ID: ``` providers: aws: enabled: true regions: - us-east-1 cloudtrail: # Replace with your actual AWS Account ID s3_bucket: "tfdrift-cloudtrail-YOUR-AWS-ACCOUNT-ID-us-east-1" state: backend: "s3" # Replace with your actual AWS Account ID s3_bucket: "tfdrift-terraform-state-YOUR-AWS-ACCOUNT-ID" s3_key: "production-test/terraform.tfstate" s3_region: "us-east-1" ``` ### 步骤 3:获取您的 AWS 账户 ID 如果您不知道您的 AWS 账户 ID: ``` # 方法 1: 使用 AWS CLI aws sts get-caller-identity --query Account --output text # 方法 2: 检查 AWS Console # AWS Console → 右上角 → 账户 ID ``` ### 步骤 4:配置 AWS 凭证 确保您的 AWS 凭证已配置: ``` # 选项 1: AWS CLI 配置 aws configure # 选项 2: 环境变量 export AWS_ACCESS_KEY_ID="your-access-key" export AWS_SECRET_ACCESS_KEY="your-secret-key" export AWS_REGION="us-east-1" # 选项 3: IAM Role (推荐用于 EC2/ECS) # 附加具有适当权限的 IAM role ``` ### 步骤 5:验证配置 ``` # 测试 AWS 认证 aws sts get-caller-identity # 启动 TFDrift-Falco docker compose up -d ``` **重要提示:** - ⚠️ **永远不要将 `config.yaml` 提交到版本控制系统** - 它已在 `.gitignore` 中 - ✅ 使用 `config.yaml.example` 作为模板 - 🔒 使用 IAM 用户(而非 root 账户)以提高安全性 - 📝 关于 GCP 配置,请参阅 [GCP 设置指南](docs/gcp-setup.md) ## 🏭 生产环境部署 TFDrift-Falco 提供生产就绪的 **REST API + WebSocket + SSE + React UI**! ### 🚀 API Server 模式 ``` # 以 API server 模式启动 docker-compose up -d # 访问: # Frontend UI: http://localhost:3000 # Backend API: http://localhost:8080/api/v1 # WebSocket: ws://localhost:8080/ws # SSE Stream: http://localhost:8080/api/v1/stream ``` ### 📡 REST API 端点 - `GET /api/v1/graph` - 因果关系图 (Cytoscape 格式) - `GET /api/v1/drifts` - Drift 告警列表 (支持过滤) - `GET /api/v1/events` - Falco 事件列表 - `GET /api/v1/state` - Terraform state 概览 - `GET /api/v1/stats` - 统计信息 - `GET /health` - 健康检查 **详情:** [API 文档](docs/API.md) ### 🌐 React Web UI ![TFDrift UI](https://via.placeholder.com/800x400?text=TFDrift+Web+UI) #### 三种视图模式 1. **📊 Graph View** - 因果关系可视化 - 带有官方 AWS/Kubernetes 图标的 React Flow - 交互式节点操作 - 分层、Dagre、力导向、圆形布局 2. **📋 Table View** - Drift 事件历史 - 显示 100+ 个事件列表 - 过滤 (严重性、提供商、搜索) - 排序功能 (最新、严重性顺序) - 详情面板 (变更前/后值、用户信息、CloudTrail) 3. **⚡ Split View** - Graph + Table 同时显示 (推荐) - 左侧:因果关系图 - 右侧:Drift 历史表 + 详情面板 **主要特性:** - 🎯 **官方图标** - AWS React Icons + Kubernetes 官方 SVG - 📊 **实时过滤** - 严重性、提供商、资源类型 - ⚡ **WebSocket/SSE Ready** - 实时通知 (已准备) - 🔍 **大规模 Graph 支持** - 1000+ 节点 (LOD, Clustering 就绪) - 📱 **响应式设计** - Tailwind CSS #### 开发环境 ``` cd ui npm install npm run dev # 访问 http://localhost:5173/ ``` ### 🐳 Docker Compose (推荐) ``` services: backend: image: tfdrift-falco:latest ports: - "8080:8080" # API server - "9090:9090" # Prometheus metrics command: ["--server", "--api-port", "8080"] frontend: image: tfdrift-frontend:latest ports: - "3000:8080" # Web UI environment: - VITE_API_BASE_URL=http://backend:8080/api/v1 ``` ### ☸️ Kubernetes 部署 ``` # Helm chart (即将推出) helm install tfdrift ./charts/tfdrift-falco # 或者使用 kubectl kubectl apply -f k8s/ ``` ### 📦 CI/CD 包含 GitHub Actions 工作流: - ✅ 后端测试 - ✅ 前端测试 - ✅ Docker 多平台构建 (amd64, arm64) - ✅ 安全扫描 (Trivy + Gosec) - ✅ Codecov 集成 **详情:** [部署指南](docs/deployment.md) ## 🔌 输出模式 (v0.4.0 新增) TFDrift-Falco 现在输出 **结构化事件**,便于与 SIEM、SOAR 和监控系统集成。 ### JSON 输出 (NDJSON) ``` # 仅机器可读 JSON 事件 tfdrift --auto --output json # 输出 (换行符分隔 JSON): {"event_type":"terraform_drift_detected","provider":"aws","resource_type":"aws_security_group","resource_id":"sg-12345",...} {"event_type":"terraform_drift_detected","provider":"aws","resource_type":"aws_instance","resource_id":"i-67890",...} ``` **适用于:** - `jq` - `tfdrift --auto --output json | jq '.resource_type'` - Fluent Bit / Fluentd - Vector - Datadog Agent - Sysdig Agent - SIEM 平台 ### 人类可读 + JSON ``` # 人类可读和 JSON (用于调试) tfdrift --auto --output both ``` 输出到: - **stderr**: 人类可读日志 - **stdout**: JSON 事件 (NDJSON) ### 事件 Schema ``` { "event_type": "terraform_drift_detected", "provider": "aws", "account_id": "123456789012", "resource_type": "aws_security_group", "resource_id": "sg-12345", "change_type": "modified", "detected_at": "2025-01-10T12:34:56Z", "source": "tfdrift-falco", "severity": "critical", "region": "us-west-2", "user": "admin@example.com", "cloudtrail_event": "AuthorizeSecurityGroupIngress", "version": "1.0.0" } ``` ## 🔗 Webhook 集成 (v0.4.1 新增) 将 drift 事件发送到 **任何 webhook endpoint** - Slack, Teams, PagerDuty 或自定义 API。 ### 快速示例 #### Slack 集成 ``` # config.yaml output: webhook: url: "https://hooks.slack.com/services/YOUR/WEBHOOK/URL" method: POST ``` Drift 事件显示为格式化的 Slack 消息,包含: - 按严重性进行颜色编码 (🚨 Critical = 红色, ⚠️ High = 橙色) - 资源详情 - 用户和区域信息 - CloudTrail 事件关联 #### Microsoft Teams ``` output: webhook: url: "https://outlook.office.com/webhook/YOUR/WEBHOOK/URL" method: POST ``` #### 带 Auth 的自定义 API ``` output: webhook: url: "https://your-api.com/drift-events" method: POST headers: Authorization: "Bearer YOUR_TOKEN" X-Custom-Header: "custom-value" timeout: 30s max_retries: 5 retry_delay: 2s ``` ### 功能特性 ✅ **自动重试** - 指数退避 (1s → 2s → 4s → 8s...) ✅ **超时处理** - 可配置超时 (默认:10s) ✅ **自定义 Headers** - 添加 auth token,自定义 headers ✅ **多种 Methods** - POST, PUT, PATCH ✅ **格式助手** - 内置 Slack & Teams 格式化器 ### Webhook 负载 发送到您的 endpoint 的原始 JSON 负载: ``` { "event_type": "terraform_drift_detected", "provider": "aws", "resource_type": "aws_security_group", "resource_id": "sg-12345", "change_type": "modified", "severity": "critical", ... } ``` **要求:** - Terraform 已初始化的目录 (`.terraform/` 存在) - Falco 运行且配置了 CloudTrail 插件 (AWS) 或 gcpaudit 插件 (GCP) - 已配置 AWS 凭证 (用于 AWS) 或已配置 GCP 凭证 (用于 GCP) ## 🧩 概述 **TFDrift-Falco** 通过结合以下组件,**实时**检测您云环境中的手动(非 IaC)变更: - 运行 **Falco** 安全监控,配合 CloudTrail 插件 (AWS) 或 gcpaudit 插件 (GCP) - **Falco gRPC API** 用于实时事件流 - **Terraform State** 对比 与执行定期静态扫描的传统 drift 检测工具(如 `driftctl` 或 `tfsec`)不同,TFDrift-Falco 提供由 Falco 云审计日志插件驱动的 **持续、事件驱动的 drift 检测**。 ### 🚨 示例用例 ``` Someone disables termination protection on an EC2 instance via AWS Console ↓ CloudTrail event captured by Falco CloudTrail plugin ↓ Falco rule triggers and sends event via gRPC ↓ TFDrift-Falco receives event and compares with Terraform state ↓ Instant Slack alert with user identity and change details ``` ## 📖 为什么选择 Falco? - 一个故事 **完美的蓝图与见证者** 想象一座城市,有一位才华横溢的建筑师,他在**蓝图** (Terraform) 中细致地记录了一切。每座建筑、每条道路、每扇大门——都完美地绘制了出来。蓝图代表了“理想的城市”。 但一天晚上,有人秘密更换了一扇大门。到了早上,一把锁被加了上去。然而蓝图……却没有显示任何变化。 第二天,建筑师穿过城市,将现实与蓝图进行比对。终于,他们发现:*“……啊,不一样了。”* 但这太迟了。他们只能看到: - ✅ **什么**改变了 - ❌ **谁**做的 - ❌ **什么时间**发生的 - ❌ **为什么**要这样做 **蓝图只讲述结果,而非行动。** ### Falco 登场:见证者 于是,这座城市雇佣了 **Falco**——不是建筑师,不是设计师,而是一名**见证者**。Falco 的工作单一且至关重要: Falco 不建造。Falco 不绘制地图。Falco 只是观察: - **谁**触碰了大门 - **什么时间**做的 - 是**哪一扇**大门 - 他们的**意图**是什么 不是在变更之后——而是在**变更发生的那一刻**。 午夜时分,Falco 观察到一个陌生人从异常的路径接近大门,伸手去抓锁。就在那一瞬间,Falco 发出警报: ### 蓝图与见证者的会面 建筑师听取了 Falco 的报告: - *“谁触碰了它?”* - *“什么时候?”* - *“哪扇大门?”* 建筑师打开蓝图并意识到: 在那一刻,他们都明白了: **蓝图** → 知道*应该存在什么* **见证者** → 知道*实际发生了什么* 单靠任何一方都无法保护这座城市。 ### 为什么选择 Falco? Falco 的特别之处在于它讲述的是**行动,而不仅仅是结果**: - 不是状态,而是**行为** - 不是差异,而是**意图** - 不是资源,而是**人** 这就是为什么 Falco 能够回答: ### 现代城市 (云) 今天的城市不仅仅由人类构建: - Bots - CI/CD pipelines - 自动化 - AI agents 变更发生在一瞬间。 这就是为什么我们需要的不止是事后审计。 我们需要**事件发生时在场的人**。 **一句话概括:** 这就是为什么将 Falco 放置在您的基础设施之间意味着: **为您的云添加一名“见证者”。** ## 🎯 核心特性 - ⚡ **实时检测** - 订阅 Falco gRPC 输出以进行即时事件处理 - 🦅 **Falco 驱动** - 使用 Falco 的 CloudTrail 插件 (AWS) 和 gcpaudit 插件 (GCP) 进行事件监控 - 🧩 **Terraform State 对比** - 检测偏离 IaC 定义的情况 - 🔒 **安全上下文** - 关联用户身份 (IAM user, API key, service account) - 🔔 **多通知渠道** - Slack, Discord, Falco output, Webhook - 🌐 **多云支持** - AWS (411 events, 23 services), GCP (100+ events, 12+ services), Azure (计划中) - 🎨 **可扩展规则** - 在 YAML 中定义自定义 Falco 规则 - 🐳 **容器就绪** - 作为 sidecar 或独立容器运行 - 📊 **生产就绪** - 全面的负载测试和监控框架 ## 📋 支持的 AWS 服务 TFDrift-Falco v0.5.0 监控 23 个 AWS 服务的 **411 个 CloudTrail 事件**: | Service | Events | Coverage | Priority | |---------|--------|----------|----------| | **CloudWatch** 📊 | 66 | Alarms, Dashboards, Metrics, Log Groups, Composite Alarms, Metric Streams, Insights | High | | **VPC/Networking** 🔒 | 40 | Security, VPC, Subnets, Route Tables, Gateways, ACLs, Endpoints, Peering, Transit Gateway, Flow Logs, Network Firewall | Critical | | **RDS** 🗃️ | 37 | Instances, Clusters, Snapshots, Parameter Groups, Subnet Groups, Option Groups, Replicas | High | | **API Gateway** 🌐 | 32 | REST APIs, Resources, Methods, Deployments, Stages, Models, Authorizers | High | | **IAM** ✅ | 25 | Roles, Users, Groups, Policies, Access Keys, Instance Profiles, Tags | Critical | | **ELB/ALB** ⚖️ | 22 | Load Balancers, Target Groups, Listeners, Rules, SSL Certificates | High | | **S3** 🪣 | 21 | Buckets, Policies, Encryption, Versioning, Lifecycle, Replication, CORS, Website, Logging | High | | **EC2** 💻 | 17 | Instances, AMIs, EBS Volumes, Snapshots, Network Interfaces | High | | **ElastiCache** 🗄️ | 16 | Cache Clusters, Replication Groups, Parameter Groups, User Groups | High | | **SageMaker** 🤖 | 16 | Endpoints, Training Jobs, Model Packages, Notebook Instances | High | | **DynamoDB** 📊 | 14 | Tables, PITR, Backups, Global Tables, Streams, Monitoring | High | | **Lambda** ⚡ | 13 | Functions, Event Sources, Permissions, Concurrency, Aliases, Versions | High | | **Kinesis** 🌊 | 13 | Streams, Consumers, Firehose, Analytics Applications | Medium | | **EKS** ☸️ | 12 | Clusters, Node Groups, Addons, Fargate Profiles | High | | **Auto Scaling** 📈 | 10 | ASGs, Launch Configurations, Policies, Scheduled Actions | Medium | | **CloudFormation** 📚 | 10 | Stacks, Stack Sets, Change Sets | High | | **KMS** 🔐 | 10 | Keys, Aliases, Rotation, Deletion, Key Policies | Critical | | **ECS** 🐳 | 8 | Services, Task Definitions, Clusters, Capacity Providers | High | | **WAF/WAFv2** 🛡️ | 8 | Web ACLs, Rule Groups, IP Sets, Regex Pattern Sets | High | | **AWS Backup** 💾 | 7 | Backup Plans, Backup Vaults, Recovery Points, Backup Jobs | Medium | | **Step Functions** 🔄 | 5 | State Machines, Executions, Tags | Medium | | **AWS Glue** 🔗 | 5 | Databases, Tables, Jobs, Crawlers | Medium | | **EventBridge** 📡 | 4 | Rules, Targets, Event Buses | Medium | | **ECR** 📦 | 1 | Repository Policies | Medium | **总计**:23 个服务的 411 个事件 | 详情请参阅 [AWS 资源覆盖分析](./docs/AWS_RESOURCE_COVERAGE_ANALYSIS.md) ## 📋 支持的 GCP 服务 TFDrift-Falco v0.5.0 监控 12+ 个服务的 **100+ 个 GCP Audit Log 事件**: | Service | Events | Coverage | Priority | |---------|--------|----------|----------| | **Compute Engine** 💻 | 30+ | Instances, Disks, Machine Types, Metadata, Networks, Firewalls | Critical | | **Cloud Storage** 🗄️ | 15+ | Buckets, Objects, IAM Bindings, ACLs, Lifecycle | High | | **Cloud SQL** 🗃️ | 10+ | Instances, Databases, Users, Backups | High | | **GKE** ☸️ | 10+ | Clusters, Node Pools, Workloads | High | | **Cloud Run** 🏃 | 8+ | Services, Revisions, IAM Policies | High | | **IAM** ✅ | 8+ | Service Accounts, Roles, Bindings, Keys | Critical | | **VPC/Networking** 🔒 | 10+ | Firewalls, Routes, Subnets, Peering | Critical | | **Cloud Functions** ⚡ | 5+ | Functions, Triggers, IAM Policies | Medium | | **BigQuery** 📊 | 5+ | Datasets, Tables, IAM Policies | Medium | | **Pub/Sub** 📨 | 5+ | Topics, Subscriptions, IAM Policies | Medium | | **KMS** 🔐 | 5+ | Keys, KeyRings, IAM Policies | Critical | | **Secret Manager** 🔒 | 3+ | Secrets, Versions, IAM Policies | High | **总计**:12+ 个服务的 100+ 个事件 | 配置详情请参阅 [GCP 设置指南](./docs/gcp-setup.md) ## 🏗️ 架构 ``` graph TB A[AWS CloudTrail] --> B[Falco
CloudTrail Plugin] A2[GCP Audit Logs] --> B2[Falco
gcpaudit Plugin] B --> C[Falco Rules
Engine] B2 --> C C --> D[Falco gRPC
Output Stream] D --> E[TFDrift-Falco
Subscriber] F[Terraform State
Local/S3/GCS] --> E E --> G[Drift Engine] G --> H{Drift Detected?} H -->|Yes| I[Enrichment
+ Context] H -->|No| J[Log Only] I --> K[Notification
Manager] K --> L[Slack] K --> M[Discord] K --> N[Webhook] style E fill:#4A90E2 style G fill:#FFA500 style I fill:#50C878 style B fill:#00B4AB style B2 fill:#00B4AB ``` ### 组件 | Component | Description | |-----------|-------------| | **Falco Subscriber** | 连接到 Falco gRPC API 并订阅 CloudTrail 事件 | | **Terraform State Loader** | 定期同步 Terraform state (本地/远程) | | **Drift Engine** | 比较 IaC 定义与运行时变更 | | **Context Enricher** | 添加用户身份、资源标签、变更历史 | | **Notifier** | 向配置的渠道发送告警 | ## 📊 代码质量与测试 TFDrift-Falco 通过全面的测试和持续集成保持高代码质量标准: ### 测试覆盖率:80%+ 🎯 - **Unit Tests**:所有核心包 (detector, falco, diff, config) - **Integration Tests**:端到端 drift 检测工作流 - **Table-Driven Tests**:高效的边界情况覆盖 - **CI/CD**:对每个 PR 进行自动化测试并强制执行覆盖率阈值 (78%) ### 代码质量工具 - ✅ **golangci-lint**:启用 15+ 个 linter 的静态分析 - ✅ **Snyk**:依赖漏洞扫描 (每周) - ✅ **GoSec**:专注于安全的静态分析 - ✅ **Nancy**:Go 依赖检查器 - ✅ **go vet**:官方 Go 静态分析器 - ✅ **staticcheck**:高级 Go linter ### 架构质量 - 📁 **Single Responsibility Principle**:模块化设计,文件聚焦 (<200 行) - 🧩 **Dependency Injection**:可测试组件,支持 mock - 🔄 **Clean Refactoring**:完成重大重构 (1,410 行 → 17 个模块化文件) - 📝 **Comprehensive Documentation**:内联注释和包文档 ### 近期成就 - 测试覆盖率从 36.9% 提升至 80.0% ✅ - 将 3 个大文件 (513, 426, 473 行) 重构为聚焦模块 ✅ - 消除所有 500+ 行文件 (测试除外) ✅ - 解决所有关键 golangci-lint 警告 ✅ 阅读更多:[测试覆盖率 80% 达成文章](./docs/test-coverage-80-achievement.md) ## 🐳 使用 Docker 快速开始 (最简单) **使用官方 Docker 镜像在 30 秒内开始:** ``` # 拉取并运行官方镜像 docker run -d \ --name tfdrift-falco \ -e TF_STATE_BACKEND=s3 \ -e TF_STATE_S3_BUCKET=my-terraform-state \ -e TF_STATE_S3_KEY=prod/terraform.tfstate \ -e AWS_REGION=us-east-1 \ -v ~/.aws:/root/.aws:ro \ ghcr.io/higakikeita/tfdrift-falco:latest ``` **查看日志:** ``` docker logs -f tfdrift-falco ``` **在 GitHub Container Registry 上可用:** - 🚀 `ghcr.io/higakikeita/tfdrift-falco:latest` - 最新稳定版 - 📌 `ghcr.io/higakikeita/tfdrift-falco:v0.2.0-beta` - 特定版本 - 🔖 查看所有标签:https://github.com/higakikeita/tfdrift-falco/pkgs/container/tfdrift-falco ## 🚀 完整安装指南 ### 前置条件 - Go 1.21 或更高版本 (用于从源码构建) - **Falco 0.35+** 配合 CloudTrail 插件 (AWS) 或 gcpaudit 插件 (GCP) - [AWS 设置](docs/falco-setup.md) | [GCP 设置](docs/gcp-setup.md) - Terraform 1.0+ - 已配置 AWS CLI (用于 AWS 支持) 或已配置 gcloud CLI (用于 GCP 支持) - **Docker** (推荐用于最简单的设置) ### 安装 #### 选项 1:二进制发布版 ``` # 下载最新版本 curl -LO https://github.com/keitahigaki/tfdrift-falco/releases/latest/download/tfdrift-linux-amd64 chmod +x tfdrift-linux-amd64 sudo mv tfdrift-linux-amd64 /usr/local/bin/tfdrift ``` #### 选项 2:从源码构建 ``` git clone https://github.com/keitahigaki/tfdrift-falco.git cd tfdrift-falco go build -o tfdrift ./cmd/tfdrift ``` #### 选项 3:Docker (推荐 ⭐) **官方镜像在 GitHub Container Registry (GHCR) 上可用** ``` # 拉取最新的官方镜像 docker pull ghcr.io/higakikeita/tfdrift-falco:latest # 或者使用特定版本 docker pull ghcr.io/higakikeita/tfdrift-falco:v0.2.0-beta # 使用 Docker 运行 docker run -d \ --name tfdrift-falco \ -v $(pwd)/config.yaml:/config/config.yaml:ro \ -v ~/.aws:/root/.aws:ro \ ghcr.io/higakikeita/tfdrift-falco:latest \ --config /config/config.yaml ``` **使用环境变量快速开始:** ``` docker run -d \ --name tfdrift-falco \ -e TF_STATE_BACKEND=s3 \ -e TF_STATE_S3_BUCKET=my-terraform-state \ -e TF_STATE_S3_KEY=prod/terraform.tfstate \ -e AWS_REGION=us-east-1 \ -e FALCO_HOSTNAME=localhost \ -e FALCO_PORT=5060 \ -v ~/.aws:/root/.aws:ro \ ghcr.io/higakikeita/tfdrift-falco:latest ``` **从源码构建 (用于开发):** ``` # 本地构建镜像 make docker-build # 运行本地构建的镜像 docker run -d \ --name tfdrift-falco \ -v $(pwd)/config.yaml:/config/config.yaml:ro \ -v ~/.aws:/root/.aws:ro \ tfdrift-falco:latest \ --config /config/config.yaml ``` #### 选项 4:Docker Compose (推荐) 运行 TFDrift-Falco 及其所有依赖项的最简单方法: ``` # 启动完整 stack (Falco + TFDrift) make docker-compose-up # 查看日志 make docker-compose-logs # 停止服务 make docker-compose-down ``` 有关详细的 Docker 和 Kubernetes 部署说明,请参阅 [部署指南](docs/deployment.md)。 ### 配置 创建 `config.yaml`: ``` # Cloud Provider 配置 providers: aws: enabled: true regions: - us-east-1 - us-west-2 state: backend: "s3" # local, s3, gcs s3_bucket: "my-terraform-state" s3_key: "prod/terraform.tfstate" gcp: enabled: true projects: - my-project-123 - my-project-456 state: backend: "gcs" # local, s3, gcs gcs_bucket: "my-terraform-state" gcs_prefix: "prod" # Falco 集成 (必需) falco: enabled: true hostname: "localhost" # Falco gRPC server hostname port: 5060 # Falco gRPC server port cert_file: "" # Optional: client certificate for mTLS key_file: "" # Optional: client key for mTLS ca_root_file: "" # Optional: CA root certificate # 漂移检测规则 drift_rules: - name: "EC2 Instance Modification" resource_types: - "aws_instance" watched_attributes: - "disable_api_termination" - "instance_type" - "security_groups" severity: "high" - name: "IAM Policy Change" resource_types: - "aws_iam_policy" - "aws_iam_role" watched_attributes: - "policy" - "assume_role_policy" severity: "critical" - name: "GCP Compute Instance Modification" resource_types: - "google_compute_instance" watched_attributes: - "metadata" - "labels" - "deletion_protection" severity: "high" - name: "GCP Firewall Rule Change" resource_types: - "google_compute_firewall" watched_attributes: - "allowed" - "denied" - "source_ranges" severity: "critical" # 通知渠道 notifications: slack: enabled: true webhook_url: "https://hooks.slack.com/services/YOUR/WEBHOOK/URL" channel: "#security-alerts" discord: enabled: false webhook_url: "https://discord.com/api/webhooks/..." falco_output: enabled: true priority: "warning" webhook: enabled: false url: "https://your-siem.example.com/webhook" headers: Authorization: "Bearer YOUR_TOKEN" # 日志 logging: level: "info" # debug, info, warning, error format: "json" # json, text ``` ### 运行 ``` # 使用配置文件运行 tfdrift --config config.yaml # 使用环境变量运行 export TFDRIFT_AWS_REGIONS="us-east-1,us-west-2" export TFDRIFT_SLACK_WEBHOOK="https://hooks.slack.com/..." tfdrift # 以 daemon 模式运行 tfdrift --config config.yaml --daemon # Dry-run 模式 (无通知) tfdrift --config config.yaml --dry-run ``` ## 📊 示例输出 ### 控制台输出 ``` [2025-01-15 10:30:45] INFO Starting TFDrift-Falco v0.1.0 [2025-01-15 10:30:45] INFO Loaded Terraform state: 142 resources [2025-01-15 10:30:46] INFO Connected to Falco socket [2025-01-15 10:30:46] INFO Listening for CloudTrail events... [2025-01-15 10:35:12] ALERT Drift Detected! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Resource: aws_instance.webserver Type: Manual Modification Severity: HIGH Changed Attribute: disable_api_termination: false → true Context: User: admin-user@example.com Source: AWS Console (IAM User) IP Address: 203.0.113.42 Region: us-east-1 Timestamp: 2025-01-15T10:35:10Z CloudTrail: EventID: a1b2c3d4-5678-90ab-cdef-1234567890ab EventName: ModifyInstanceAttribute Terraform: Resource: aws_instance.webserver Module: modules/ec2 File: main.tf:45 Recommendation: - Review change with user admin-user@example.com - Run 'terraform plan' to sync state - Update Terraform code if change is intentional ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` ### Slack 通知 ![Slack Alert Example](https://raw.githubusercontent.com/higakikeita/tfdrift-falco/main/docs/images/slack-example.png) ``` 🚨 Drift Detected: aws_instance.webserver Changed: disable_api_termination = false → true User: admin-user@example.com (AWS Console) Region: us-east-1 Severity: HIGH CloudTrail EventID: a1b2c3d4-5678-90ab-cdef-1234567890ab [View in Console] [Terraform Code] [Runbook] ``` ## 🧪 使用案例 有关详细的配置示例、告警模式和集成指南,请参阅 [使用案例文档](docs/USE_CASES.md)。 ### 1. 安全与合规 🔒 **实时检测未经授权的基础设施变更** - 手动安全组修改 (例如,向 0.0.0.0/0 开放端口 22) - Terraform 管理之外的 IAM 策略变更 - 加密设置禁用 (RDS, S3, EBS 等) **示例**:开发人员通过 AWS 控制台修改生产环境安全组 → 立即向 Slack 发送严重告警 ### 2. 成本管理 💰 **即时检测具有成本影响的资源变更** - 实例类型变更 (t3.micro → m5.8xlarge) - 存储卷扩容 (100GB → 1TB) - EBS 卷类型变更 (gp2 → io2) **示例**:EC2 从 t3.micro 升级到 m5.8xlarge → 向 Slack 发送带有成本影响 (+$1.52/hr) 的告警 ### 3. 审计与治理 📋 **完整的变更历史和用户跟踪** - 完整记录谁在何时更改了什么 - SIEM 系统集成 (JSON 事件输出) - 合规性报告生成 (SOC2, PCI-DSS, HIPAA) **示例**:所有基础设施变更以 JSON 格式转发到 Splunk 并作为审计跟踪保存 ### 4. GitOps 执行 🔧 **强制执行 Infrastructure-as-Code 纪律** - 即时检测并告警基于控制台的变更 - 防止未经代码审查的变更 - 自动配置 drift 检测 **示例**:通过 AWS 控制台修改 Terraform 管理的资源 → 立即向团队 Slack 频道告警 ### 5. 事件响应 🚨 **实时检测安全事件** - 后门 IAM 用户创建检测 - 权限提升尝试检测 - 数据泄露风险变更 (S3 存储桶被公开) **示例**:创建 IAM 用户 → 立即触发 PagerDuty 事件,通知值班工程师 ### 6. 多云治理 🌐 **AWS + GCP 的统一监控** - 同时监控 AWS CloudTrail 和 GCP Audit Logs - 跨多个云提供商的一致变更管理 - 统一的告警格式和仪表板 **示例**:AWS 和 GCP 基础设施变更在单个 Grafana 仪表板中可视化 📚 **有关详细的用例、配置示例和集成模式,请参阅 [使用案例文档](docs/USE_CASES.md)。** ## 📘 最佳实践 在生产环境中安全高效地运行 TFDrift-Falco 的最佳实践。 ### 生产环境部署 🚀 - **High Availability**:以 Active-Passive 配置部署 2 个以上副本 - **Resource Sizing**:根据工作负载分配合适的 CPU/内存 (Small: 128Mi/100m, Medium: 256Mi/250m, Large: 512Mi/500m) - **Multi-Region**:每个区域运行独立的 TFDrift-Falco 实例 ### 安全 🔒 - **IAM Permissions**:最小权限原则 (Terraform State 只读) - **Network Security**:对 Falco gRPC 连接使用 mTLS,使用 Kubernetes Network Policies 限制通信 - **Secrets Management**:使用 Kubernetes Secrets/AWS Secrets Manager/GCP Secret Manager 管理 webhook URL 和凭证 ### 卓越运营 📊 - **Logging**:将结构化日志 (JSON) 转发到外部日志系统 - **Monitoring**:暴露 Prometheus 指标,使用 Grafana 可视化 - **Alerting**:立即通知 Critical/High 级别的 drift (Slack/PagerDuty) - **Backup**:定期备份 Terraform State (启用 S3 版本控制) ### 配置 🔧 - **Drift Rules**:针对特定环境设计规则 (Production: 所有变更, Staging: 仅) - **Event Filtering**:使用 Falco 规则预先过滤不必要的事件 - **State Refresh**:根据环境规模设置刷新间隔 (Small: 5m, Medium: 10m, Large: 15m) ### 故障排除 🔍 常见问题及解决方案: - **"Cannot connect to Falco gRPC"** → 验证 Falco 启动,检查 gRPC 配置,验证网络连接 - **"Too many alerts (False Positives)"** → 缩小 watched_attributes,排除非 Terraform 管理的资源 - **"High memory usage"** → 延长 state 刷新间隔,调整 worker 数量 - **"High detection latency"** → 使用 S3 VPC endpoint,减少通知超时 📚 **有关详细的配置示例、故障排除和性能调优,请参阅 [最佳实践文档](docs/BEST_PRACTICES.md)。** ## 🧩 集成示例 ### 与 Sysdig Secure 集成 ``` notifications: webhook: enabled: true url: "https://secure.sysdig.com/api/v1/events" headers: Authorization: "Bearer ${SYSDIG_API_TOKEN}" payload_template: | { "event": { "name": "Terraform Drift Detected", "description": "{{ .ResourceType }} {{ .ResourceName }} was modified", "severity": "{{ .Severity }}", "tags": { "user": "{{ .User }}", "resource": "{{ .ResourceID }}", "cloud": "{{ .Provider }}" } } } ``` ### 与 Falco Rules 集成 ``` # falco-rules.yaml - rule: Terraform Managed Resource Modified desc: Detect modifications to Terraform-managed resources condition: > evt.type = aws_api_call and aws.eventName in (ModifyInstanceAttribute, PutBucketPolicy, UpdateAssumeRolePolicy) and not user.name startswith "terraform-" output: > Terraform resource modified manually (user=%user.name resource=%aws.resource.id event=%aws.eventName) priority: WARNING tags: [terraform, drift, iac] ``` ### 与 Grafana/Prometheus 集成 TFDrift-Falco 暴露 Prometheus 指标: ``` # 按严重程度划分的漂移事件 tfdrift_events_total{severity="critical"} 5 tfdrift_events_total{severity="high"} 23 tfdrift_events_total{severity="medium"} 45 # 按资源类型划分的漂移事件 tfdrift_events_by_type{type="aws_instance"} 12 tfdrift_events_by_type{type="aws_iam_role"} 8 # 检测延迟 tfdrift_detection_latency_seconds{quantile="0.95"} 2.3 ``` ## 📊 Grafana 仪表板 (生产就绪 ✅) **使用预构建的 Grafana 仪表板进行实时 drift 监控** ### 快速开始 (5 分钟) ``` cd dashboards/grafana ./quick-start.sh ``` 这将打开 http://localhost:3000,显示 3 个预构建的仪表板,展示示例 drift 事件。 ### 功能特性 ✅ **3 个预构建仪表板** - **Overview**:总 drifts,严重性细分,时间线视图 - **Diff Details**:配置变更,预期与实际对比 - **Heatmap & Analytics**:Drift 模式和趋势分析 ✅ **实时监控** - 5-30 秒自动刷新 - 颜色编码的严重性级别 - 多维过滤 ✅ **告警** - 6 个预配置的告警规则 - Slack/Email/Webhook 通知支持 - 按严重性智能路由 ✅ **生产就绪** - 全面的文档 ([入门指南](dashboards/grafana/GETTING_STARTED.md)) - 自动化集成测试 (100% 通过率) - 性能优化 (<2s 查询) ### 文档 - 🚀 **[入门指南](dashboards/grafana/GETTING_STARTED.md)** - 面向最终用户的完整设置 - 🚨 **[告警配置](dashboards/grafana/ALERTS.md)** - Slack/Email 告警设置 - 🎨 **[自定义指南](dashboards/grafana/CUSTOMIZATION_GUIDE.md)** - 仪表板自定义 - 📖 **[测试结果](dashboards/grafana/INTEGRATION_TEST_RESULTS.md)** - 集成测试报告 ### 架构 ``` TFDrift-Falco → JSON Logs → Promtail → Loki → Grafana Dashboards ↓ Alerting → Slack/Email ``` ## 🗺️ 路线图 有关详细的服务扩展计划,请参阅 **[AWS 覆盖路线图](./docs/AWS_COVERAGE_ROADMAP.md)**。 ### 第一阶段:MVP (✅ 完成 - v0.2.0-beta) - [x] AWS CloudTrail 集成 - [x] Terraform state 对比 (本地) - [x] Slack 通知 - [x] 基础 drift 规则 (EC2, IAM, S3) - [x] Falco 事件集成 - [x] Docker 容器支持 - [x] 10 个 AWS 服务的 95 个 CloudTrail 事件 ### 第 1.5 阶段:增强 AWS 覆盖 (✅ 完成 - v0.3.0) - [x] **ECS** - Services, Task Definitions, Clusters, Capacity Providers (13 events) - [x] **EKS** - Clusters, Node Groups, Addons, Fargate Profiles (12 events) - [x] **Lambda Enhanced** - 额外的函数配置 (10 events) - [x] **EC2 Enhanced** - 网络接口,卷,快照 (17 events) - [x] **ElastiCache** - Redis/Memcached 集群 (12 events) - [x] **Auto Scaling** - ASG 配置和策略 (10 events) - [x] **RDS Enhanced** - 参数组,子网组,快照,只读副本,选项组 (31 events) - [x] **DynamoDB Enhanced** - PITR,备份,全局表,流 (14 events total) - [x] **VPC Enhanced** - Peering, Transit Gateway, Flow Logs, Network Firewall (42 events total) - [x] **SageMaker** - Endpoints, training, model packages, notebooks (16 events) **v0.3.0 成就**:203 个 CloudTrail 事件 (原目标的 103% 🎉) **v0.5.0 成就**:23 个 AWS 服务的 411 个 CloudTrail 事件 (原目标的 **208%** 🚀) ### 第二阶段:增强检测 (✅ GCP 支持完成 - v0.5.0) - [x] **GCP Audit Logs 支持** - 12+ 服务的 100+ 事件 - [x] **GCS backend 支持** - 来自 Google Cloud Storage 的 Terraform state - [ ] Azure Activity Logs 支持 - [ ] Terraform Cloud/Enterprise 集成 - [ ] Azure Blob backend 支持 - [ ] 自定义规则 DSL ### 第三阶段:高级功能 - [ ] Web 仪表板 UI - [ ] 基于机器学习的异常检测 - [ ] 自动修复操作 - [ ] Policy-as-Code 集成 - [ ] 从 drift 生成 Terraform plan ### 第四阶段:企业功能 - [ ] 多账户/多组织支持 - [ ] RBAC 和团队管理 - [ ] 合规性报告 (SOC2, PCI-DSS, HIPAA) - [ ] 集成市场 - [ ] SaaS 服务 ## 🤝 贡献 欢迎贡献!详情请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。 ### 开发设置 ``` # 克隆 repository git clone https://github.com/keitahigaki/tfdrift-falco.git cd tfdrift-falco # 安装依赖 go mod download # 运行测试 go test ./... # 带 race detection 运行 go test -race ./... # 运行安全扫描 ./scripts/security-scan.sh # 构建 make build # 本地运行 ./tfdrift --config examples/config.yaml ``` ### 安全扫描 每次提交都会运行多个安全工具: - **Snyk**:依赖漏洞扫描 - **GoSec**:Go 代码安全审计 - **Nancy**:OSS 依赖扫描器 运行本地安全扫描: ``` ./scripts/security-scan.sh ``` 有关安全策略和报告漏洞,请参阅 [SECURITY.md](.github/SECURITY.md)。 ### 项目结构 ``` tfdrift-falco/ ├── cmd/ │ └── tfdrift/ # CLI entry point │ └── main.go ├── pkg/ │ ├── cloudtrail/ # CloudTrail event ingestion │ ├── falco/ # Falco integration │ ├── terraform/ # Terraform state parsing │ ├── detector/ # Drift detection engine │ ├── notifier/ # Notification handlers │ ├── config/ # Configuration management │ └── enricher/ # Context enrichment ├── docs/ # Documentation ├── examples/ # Example configurations ├── tests/ # Integration tests └── scripts/ # Build and deployment scripts ``` ## 📚 文档 - [架构概览](docs/architecture.md) - [Falco 设置指南 - AWS](docs/falco-setup.md) - **AWS CloudTrail 插件设置** - [Falco 设置指南 - GCP](docs/gcp-setup.md) - **GCP gcpaudit 插件设置** - [部署指南](docs/deployment.md) - **Docker, Kubernetes, Systemd 部署** - [使用指南](docs/USAGE.md) - [自动导入指南](docs/auto-import-guide.md) - [测试覆盖率成就](docs/test-coverage-80-achievement.md) ## 🛡️ 安全 如果您发现安全漏洞,请发送电子邮件至 security@example.com。所有安全漏洞将得到及时处理。 ## 📜 许可证 本项目采用 MIT 许可证 - 详情请参阅 [LICENSE](LICENSE) 文件。 ## 🙏 致谢 - [Falco Project](https://falco.org/) - 运行时安全监控 - [Sysdig](https://sysdig.com/) - 云原生安全平台 - [driftctl](https://github.com/snyk/driftctl) - Drift 检测的灵感来源 - [Terraform](https://www.terraform.io/) - Infrastructure as Code ## 📞 联系方式 - 作者:Keita Higaki - GitHub: [@keitahigaki](https://github.com/keitahigaki) - X (Twitter): [@keitah0322](https://x.com/keitah0322) - Qiita: [@keitah](https://qiita.com/keitah) **由云原生安全社区用 ❤️ 制作**
标签:AWS, CloudTrail, DevSecOps, Docker, DPI, EC2, ECS, EVTX分析, EVTX分析, Falco, Go, IaC, Ruby工具, Terraform, 上游代理, 事件驱动, 变更审计, 安全防御评估, 开源安全工具, 异常检测, 敏感词过滤, 日志审计, 漂移检测, 状态对比, 网络测绘, 自定义请求头, 请求拦截, 足迹分析, 逆向工程平台