# drift-corrector **Repository Path**: staging1/drift-corrector ## Basic Information - **Project Name**: drift-corrector - **Description**: drift-corrector - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-02-28 - **Last Updated**: 2026-02-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Linux 服务配置漂移自动修正系统 基于 Go 实现的跨节点配置漂移检测与自愈系统,运行在 Linux 用户态(User Space)。 ## 系统架构 ``` ┌─────────────────────────────────────────────────────────────────┐ │ Agent 进程 │ │ │ │ ┌──────────┐ 事件 ┌───────────┐ 漂移 ┌────────────┐ │ │ │ Watcher │ ──────▶ │ Detector │ ────────▶ │ Executor │ │ │ │(inotify) │ 防抖 │(Merkle树) │ DriftEvt │(原子替换) │ │ │ └──────────┘ └───────────┘ └────────────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ ┌──────────┐ ┌──────────┐ ┌────────────────┐ │ │ │ Debounce │ │ Baseline │ │ systemctl │ │ │ │(500ms窗口)│ │ Store │ │ reload/restart│ │ │ └──────────┘ │(tmpfs) │ └────────────────┘ │ │ └──────────┘ │ │ │ │ ▼ │ │ ┌──────────┐ ┌────────────────┐ │ │ │ Renderer │ │ Auditor │ │ │ │(掩码渲染)│ │ (JSON 审计) │ │ │ └──────────┘ └────────────────┘ │ │ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ Gossip Server (HTTP) │ │ │ │ /gossip/push /gossip/sync /gossip/health │ │ │ └──────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ Gossip 协议(随机 FanOut) ┌──────────────────────────────────┐ │ Node-A ◀──▶ Node-B ◀──▶ Node-C │ │ ↘ ↗ │ │ Node-D ◀──▶ Node-E │ └──────────────────────────────────┘ ``` ## 核心模块说明 | 模块 | 职责 | 关键技术 | |------|------|----------| | `watcher` | 监听文件系统变更 | fsnotify (inotify 封装) + 防抖 | | `merkle` | 配置树指纹管理 | Merkle Tree + 脏位懒惰更新 | | `detector` | 漂移检测 | 环境感知哈希比对 | | `executor` | 原子修正 | rename() 系统调用 + systemd reload | | `baseline` | 黄金配置管理 | tmpfs 内存存储 | | `gossip` | 跨节点共识 | HTTP Gossip 协议 | | `renderer` | 环境感知渲染 | 正则掩码 + /proc 元数据注入 | | `auditor` | 审计日志 | 结构化 JSON 日志 | ## 设计原则 ### SOLID 原则落地 **S(单一职责)**:每个包只负责一件事 - `watcher` 仅负责事件采集与防抖 - `detector` 仅负责漂移判定 - `executor` 仅负责原子修正操作 **O(开闭原则)**:通过接口扩展,无需修改已有代码 ```go // 可以替换任意检测算法实现 type Detector interface { Run(ctx context.Context, drifts chan<- DriftEvent) error } // 可以替换任意文件监控后端 type Watcher interface { Watch(paths []string) error Events() <-chan FileEvent Close() error } ``` **L(里氏替换)**:`MerkleDetector` 完全可以替换为基于 eBPF 的检测器 **I(接口隔离)**:`Auditor` 接口仅暴露必需的 3 个方法,不强制实现者关注内部状态 **D(依赖倒置)**:`Agent` 依赖接口而非具体实现,所有依赖在 `agent.New()` 中注入 ### DRY 原则落地 - `maskedFileHash` 函数统一封装"掩码+哈希"逻辑,避免重复 - `atomicReplace` 复用于修正和回滚流程 - `walkDir` 统一目录遍历逻辑 ### KISS 原则落地 - Gossip 协议用 HTTP 实现,无需引入 gRPC/Protobuf 等复杂依赖 - 防抖用 `time.AfterFunc` 实现,不需要额外框架 - 每个函数控制在 30 行以内 ## 关键算法 ### 1. 防抖(解决高频哈希抖动) ``` 事件流:MODIFY MODIFY MODIFY MODIFY ...[500ms 静默]... 触发一次检测 ↑ 重置静默窗口计时器 ``` - 监听 `IN_CLOSE_WRITE` 而非 `IN_MODIFY`(文件关闭才代表逻辑修改完成) - 静默窗口内无新事件才下发通知(可配置,默认 500ms) - 单文件超出 MaxEventRate 触发熔断,降级为定时巡检 ### 2. Merkle 树差异定位(O(log N) 复杂度) ``` Root Hash / \ /etc/nginx /etc/ssh ← 目录节点(哈希 = SHA256(子哈希拼接)) / \ / \ nginx.conf mime sshd banner ← 叶子节点(哈希 = SHA256(内容+元数据)) ↑ 漂移!只需对比路径上的 3 个节点,而非全量扫描 ``` - 脏位懒惰更新:只有被修改的路径向根传播 dirty=true - 静默窗口到期后批量重建,避免串行高频计算 ### 3. 原子修正流程 ``` [检测漂移] │ ▼ [备份当前错误文件] → /rollbacks/nginx.conf_bad_20240115_143022 │ ▼ [write golden → .drift_tmp] → rename(.drift_tmp → nginx.conf) ← 原子操作 │ ▼ [SHA-256 校验] ─── 不一致 ──▶ [rollback] ─▶ [rollback 成功] │ 一致 ▼ [systemctl reload nginx] ─── 失败 ──▶ [rollback] │ 成功 ▼ [审计日志: CORRECTED] ``` ### 4. 环境感知哈希掩码 防止节点特有字段(IP、hostname)导致跨节点误报: ``` 原始内容:bind_address = 192.168.1.10 掩码后: bind_address = {{MASKED}} ↑ 参与哈希计算的内容 ``` ## 项目结构 ``` drift-corrector/ ├── cmd/ │ └── agent/main.go # 程序入口,优雅关闭 ├── internal/ │ ├── config/config.go # YAML 配置加载与校验 │ ├── hash/ │ │ ├── hash.go # SHA-256(内容+元数据) │ │ └── stat_linux.go # Linux UID/GID 提取 │ ├── merkle/tree.go # 默克尔树(脏位懒惰更新) │ ├── baseline/store.go # 黄金配置基准库(tmpfs) │ ├── watcher/watcher.go # 文件监控 + 防抖 + 熔断 │ ├── detector/detector.go # 漂移检测引擎 │ ├── executor/executor.go # 原子修正(rename + systemd) │ ├── gossip/server.go # HTTP Gossip 跨节点共识 │ ├── renderer/renderer.go # 环境感知掩码渲染 │ ├── auditor/auditor.go # 结构化 JSON 审计日志 │ └── agent/agent.go # 顶层协调器(依赖注入) └── configs/ └── agent.yaml # 示例配置文件 ``` ## 快速开始 ### 编译 ```bash # 需要 Go 1.21+ go build -o drift-agent ./cmd/agent # 交叉编译(在 macOS 上为 Linux 构建) GOOS=linux GOARCH=amd64 go build -o drift-agent ./cmd/agent ``` ### 部署 ```bash # 1. 挂载 tmpfs(毫秒级回滚的关键) mkdir -p /run/drift-corrector mount -t tmpfs -o size=512m tmpfs /run/drift-corrector # 2. 准备配置 cp configs/agent.yaml /etc/drift-corrector/agent.yaml # 编辑 node.id、watch.paths、gossip.peers # 3. 启动(需要 root 权限以读取 /etc 和调用 systemctl) sudo ./drift-agent --config /etc/drift-corrector/agent.yaml ``` ### 查看审计日志 ```bash # 实时追踪漂移与修正事件 tail -f /var/log/drift-corrector/audit.jsonl | jq '.' # 示例输出 { "timestamp": "2024-01-15T14:30:22.123Z", "node_id": "node-web-01", "event_type": "DRIFT_DETECTED", "file_path": "/etc/nginx/nginx.conf", "actual_hash": "a3f2c1...", "golden_hash": "b8e4d2..." } { "timestamp": "2024-01-15T14:30:22.456Z", "node_id": "node-web-01", "event_type": "CORRECTED", "file_path": "/etc/nginx/nginx.conf", "service": "nginx", "success": true, "duration_ms": "12.34" } ``` ### Gossip 健康检查 ```bash curl http://localhost:9090/gossip/health | jq '.' # {"node_id":"node-web-01","root_hash":"abc123...","status":"ok"} ``` ## 扩展方向 1. **eBPF 增强**:用 eBPF 代替 inotify,在系统调用层面拦截,实现纳秒级响应 2. **Raft 强一致**:将 Gossip 替换为 Raft 协议,适用于金融等对强一致性要求极高的场景 3. **权限漂移检测**:扩展到 `/etc/passwd`、`/etc/sudoers` 的异常变更检测 4. **网络规则漂移**:检测并自动恢复被修改的 `iptables`/`nftables` 规则 5. **Prometheus 指标**:暴露 `drift_total`、`correction_duration` 等指标