diff --git a/README.md b/README.md index 23164a1..504e879 100644 --- a/README.md +++ b/README.md @@ -1,1645 +1,1086 @@ -
+# Aluer ServerGuard V5.0 -[**English**](README_EN.md) · **简体中文** - -
- -
-

- Aluer ServerGuard 徽标 -

-
- -

- Java - Spring Boot - React - Vite - DeepSeek AI - 许可证 -

- -

- 收藏 - 复刻 - 问题 - 合并请求 - 最后提交 -

+> AI 驱动的 Minecraft PaperMC 服务器全方位安全防护系统 --- -

Aluer ServerGuard

+## 项目概述 -

- 🛡️ AI 驱动的 Minecraft PaperMC 服务器安全防护与自动化运维系统 -

+Aluer ServerGuard 是一款专为 Minecraft PaperMC 服务器打造的新一代智能安全防护系统。系统采用 **Agent 架构**,通过轻量级 Paper 插件作为数据采集前端,配合外部 Spring Boot 分析引擎,实现对服务器的全方位实时防护。 -

- 为不愿在安全上妥协的 Minecraft 服主用心构建 -

- -
-

- "当 DDoS 攻击、机器人潮和零日漏洞威胁着你的 Minecraft 社区,
Aluer 以自主守护者的姿态屹立——由 DeepSeek AI 与多层内核融合引擎驱动。"
-

-
- -

- 🏗 系统架构  ·  - 🚀 快速开始  ·  - ⚙️ 配置参考  ·  - 📦 模块清单  ·  - 🌐 API 参考  ·  - 🖥 Web 控制台  ·  - 💻 命令参考  ·  - ❓ 常见问题 -

- -
- - - - - - - - - -
-
- 2-5秒
- 大模型响应 -
-
- <1毫秒
- 内核延迟 -
-
- 四级
- 防御体系 -
-
- 85+
- 安全模块 -
-
- 约200MB
- 内存占用 -
- -
- -## 目录 - -- [系统架构](#-系统架构) - - [三层决策引擎](#1-三层决策引擎) - - [Kernel 信号融合模型](#2-kernel-信号融合模型) - - [数据流全景](#3-数据流全景) -- [快速开始](#-快速开始) - - [环境要求](#环境要求) - - [本地构建](#本地构建) - - [环境变量配置](#环境变量配置) - - [首次启动](#首次启动) - - [一键安装脚本](#一键安装脚本) -- [部署指南](#-部署指南) - - [Systemd 服务](#systemd-服务) - - [sudo 权限配置](#sudo-权限配置) - - [反向代理(可选)](#反向代理可选) -- [配置参考](#️-配置参考) - - [完整配置树](#完整配置树) - - [环境变量注入表](#环境变量注入表) -- [模块清单](#-模块清单) - - [AI 决策层](#ai-决策层-comaluerai) - - [Kernel 内核层](#kernel-内核层-comaluerkernel) - - [安全防护层](#安全防护层-comaluersecurity) - - [运营控制层](#运营控制层-comaluerconsole) - - [监控采集层](#监控采集层-comaluermonitor) - - [核心服务层](#核心服务层-comaluerservice) - - [Web 交互层](#web-交互层-comaluerweb) - - [通知与报告层](#通知与报告层-comaluernotification) - - [辅助功能模块](#辅助功能模块) - - [数据模型](#数据模型-comaluermodel) -- [防御等级与自动响应](#️-防御等级与自动响应) -- [API 参考](#-api-参考) - - [系统状态 API](#系统状态-api) - - [安全态势 API](#安全态势-api) - - [健康检查 API](#健康检查-api) - - [通知与报告 API](#通知与报告-api) - - [控制台操作 API](#控制台操作-api) - - [SSH 网关 API](#ssh-网关-api) - - [备份管理 API](#备份管理-api) -- [Web 控制台](#-web-控制台) -- [Shell 命令参考](#-shell-命令参考) -- [开发指南](#-开发指南) -- [常见问题](#-常见问题) -- [许可证](#-许可证) -- [支持项目](#-支持项目) +核心特色: +- **AI 行为分析**:基于隔离森林(Isolation Forest)和时间序列预测的异常检测 +- **DeepSeek 大模型集成**:自动分析安全告警并生成防御策略 +- **全类型反作弊覆盖**:对抗 Meteor Client 等主流外挂客户端的全部 hack 模块 +- **服务器自愈能力**:TPS/CPU/内存异常自动恢复,DDoS 自动防御 +- **双模式部署**:支持 Plugin 内嵌模式和 External 外部监控模式 +- **135+ 安全模块**:覆盖反作弊、网络安全、主机安全、入侵检测、取证分析 --- -## ✨ 为什么选择 Aluer +## 版本历史 - - - - - - - - - -
-

🧠 双引擎智能决策

-

大模型(DeepSeek)+ 内核规则引擎协同工作。Sovereign 处理未知威胁,Kernel 在 1 毫秒内响应已知模式。杜绝单点决策失效。

-
-

🛡️ 全栈纵深防御

-

从 MC 协议层 → 应用 WAF → 系统防火墙 → Cloudflare 边缘节点。85+ 安全模块覆盖 L3-L7,零信任架构、蜜罐诱捕一应俱全。

-
-

📊 实时可视化控制台

-

React 19 星云控制台,SSE 实时流、性能走势条、健康探针、自动刷新——专为应急指挥官设计,一眼看清全局。

-
-

🔧 全自动运维

-

自愈编排、恢复前自动备份、定时任务、Discord/Slack 通知、HTML 攻击报告。你睡觉时,服务器自己守着自己。

-
+| 版本 | 日期 | 核心更新 | +|------|------|----------| +| V5.3 | 2026-05 | Meteor Client 世界/玩家/杂物模块对抗:SpeedMine, FastUse, NoInteract, AutoMine, VeinMiner, AutoTool, FakePlayer, PistonAura, Anchor, StashFinder | +| V5.2 | 2026-05 | Meteor Client 移动类对抗:NoSlow, Spider, Step, PacketFly, AirJump, LongJump, AntiHunger, FastFall, VClip | +| V5.1 | 2026-05 | Meteor Client 战斗类对抗:Criticals, AutoTotem, Surround, AutoTrap, AutoCrystal, AutoArmor, ChestSwap, AutoLog, Hitboxes, BowAimbot | +| V5.0 | 2026-04 | Agent 架构重构,WebSocket 实时通信,Timer/Velocity/Phase/Blink/FastBreak/ElytraFly 反作弊 | +| V4.0 | 2026-03 | KillAura/Reach/Speed/Jesus/NoFall/Scaffold/Nuker/AutoClicker 反作弊,玩家行为安全,服务器保护 | --- -## 🧬 系统架构 - -Aluer ServerGuard 部署在 Minecraft 服务器同一台主机上,通过 **RCON 协议** 与 PaperMC 服务端通信,同时管理操作系统级防火墙(iptables/ufw)和 Cloudflare 边缘防护。 - -### 1. 三层决策引擎 - -这是整个系统的核心设计——L1 负责宏观战略决策,L2 负责信号级战术判断,L3 负责执行落地。 +## 架构设计 ``` -┌──────────────────────────────────────────────────────────────┐ -│ L1: AluerSovereignEngine │ -│ 输入: 全网态势 JSON(数百个字段的压缩上下文) │ -│ 处理: 发送给 DeepSeek LLM,要求返回结构化指令 │ -│ 输出: workflow(8 种工作流之一)+ defenseLevel + reason │ -│ 周期: 每 45 秒执行一次 │ -│ 特征: LLM 主导,具备自然语言推理能力,处理模糊/新类型威胁 │ -├──────────────────────────────────────────────────────────────┤ -│ L2: AluerKernelEngine │ -│ 输入: 5 个虚拟模块从 10+ 安全子系统采集的实时信号 │ -│ 处理: 加权汇聚 → 三维压力计算 → 指令合成 │ -│ 输出: heat / resonance / control + KernelDirective │ -│ 周期: 每 30 秒一次 Pulse │ -│ 特征: 确定性规则引擎,可解释,不受 LLM 延迟/幻觉影响 │ -├──────────────────────────────────────────────────────────────┤ -│ L3: AIAutonomousService │ -│ 输入: L1 宏观指令 + L2 Kernel 指令 │ -│ 处理: 冲突仲裁 → 冷却检查 → 操作限流 → RCON 命令构造 │ -│ 输出: ban-ip / kick / whitelist / clear-lag / set-spawn-rate │ -│ 护栏: 每小时最多 12 次操作,高风险操作需双信号确认 │ -└──────────────────────────────────────────────────────────────┘ ++---------------------------------------------------------------------+ +| Aluer ServerGuard 系统架构 | ++---------------------------------------------------------------------+ +| | +| +------------------+ WebSocket +----------------+ | +| | PaperMC Server | <========================> | ServerGuard | | +| | | ws://host:8080/agent | Spring Boot | | +| | +------------+ | | +----------+ | | +| | | AluerPlugin| | EVENT ---------------> | | Security | | | +| | | (Agent) | | METRICS --------------> | | Modules | | | +| | | | | ALERT -----------------> | | (135+) | | | +| | | Bukkit | | HEARTBEAT -------------> | +----------+ | | +| | | Events | | | +----------+ | | +| | +------------+ | <-------- COMMAND ----- | | ML/AI | | | +| | | <-------- CONFIG ------ | | Engine | | | +| | Event Listeners | | +----------+ | | +| | + Combat | | +----------+ | | +| | + Block | | | DeepSeek | | | +| | + Movement | | | Analysis | | | +| | + Inventory | | +----------+ | | +| | + Chat | | +----------+ | | +| | + Command | | | Web | | | +| | + Entity | | | Dashboard | | | +| | + Packet | | +----------+ | | +| | + World | +----------------+ | +| +------------------+ | | +| | | +| +------------v-------+ | +| | Self-Healing | | +| | Shield / Kernel | | +| | Autonomy Engine | | +| +--------------------+ | ++---------------------------------------------------------------------+ ``` -**为什么需要两层决策?** Sovereign(DeepSeek)擅长理解新威胁模式,但存在 API 延迟(~2-5 秒)和偶发的非结构化输出。Kernel 是纯规则引擎,延迟 < 1ms,可以在 Sovereign 响应之前对已知威胁模式做出即时反应。两者取交集,互相兜底。 +**通信协议**:所有消息均为单行 JSON,通过 WebSocket 文本帧双向传输。 -### 2. Kernel 信号融合模型 +Agent 向 Server 发送的消息类型: +- `EVENT` -- Bukkit 事件数据(玩家移动、战斗、方块操作等) +- `METRICS` -- 服务器指标(TPS、CPU、Memory、在线人数) +- `ALERT` -- 安全告警 +- `HEARTBEAT` -- 心跳保活 +- `HANDSHAKE` -- 初始握手 +- `COMMAND_RESULT` -- 命令执行结果 -Kernel 内部运行 5 个虚拟模块(`KernelModule` 接口),每个模块从特定安全子系统采集压力信号: +Server 向 Agent 发送的指令类型: +- `COMMAND` -- 执行操作(BAN_IP, BAN_PLAYER, KICK, CLEAR_LAG 等) +- `CONFIG` -- 动态配置更新 +- `SHUTDOWN` -- 关闭连接 -| 模块 | 名称 | 数据源 | 映射向量 | 基准权重 | -|------|------|--------|----------|----------| -| `ThreatMeshModule` | 威胁网格 | DDoS / 防火墙 / IDS / 端口扫描 / 深度包检测 | `network` | 1.12 | -| `CommandLatticeModule` | 指令晶格 | 命令守卫(危险指令拦截 + RCON 爆破) | `command` | 1.18 | -| `HardeningMatrixModule` | 加固矩阵 | 安全基线审计(漏洞数 × 严重性) | `integrity` | 1.05 | -| `PerimeterWardModule` | 边界护盾 | WAF(被拦截/可疑请求 + 活跃客户端数) | `perimeter` | 0.92 | -| `EchoGridModule` | 回波网格 | 历史 IP 的压力记忆衰减 | `memory` | 0.84 | +--- -每个 Pulse 周期(默认 30s),5 个模块各自产生 0~N 个 `KernelSignal`(module + vector + pressure)。汇聚算法: +## 技术栈 -``` -对于每个信号 signal: - weighted = clamp(signal.pressure × adaptiveWeight[module], 0, 100) - vectorScores[signal.vector] += weighted - moduleScores[signal.module] += weighted +| 技术 | 版本 | 用途 | +|------|------|------| +| Java | 21 | 核心语言 | +| Spring Boot | 3.2.0 | 应用框架 | +| Maven | 3.9.6 | 构建管理 | +| PaperMC API | 1.21.1-R0.1-SNAPSHOT | Minecraft 服务端 API | +| Spring WebSocket | 3.2.0 | Agent 通信 | +| Spring Mail | 3.2.0 | 邮件告警 | +| Spring Shell | 3.1.3 | 命令行交互 | +| SnakeYAML | 2.2 | YAML 配置解析 | +| Smile | 2.6.0 | 机器学习算法库 | +| Apache Commons Math | 3.6.1 | 数学/统计计算 | +| Gson | (内嵌) | JSON 序列化 | -heat = clamp(peak_vector × 0.68 + average_vector × 0.32, 0, 100) -resonance = clamp(heat × 0.45 + second_vector × 0.18 + energized_count × 14 + signal_count × 2.2, 0, 100) -control = clamp(100 - heat × 0.62 - resonance × 0.28, 0, 100) +--- + +## 完整安全模块清单 + +### 一、反作弊 -- 战斗类(15 模块) + +| 模块名称 | 对应 Hack | 检测原理 | +|---------|----------|---------| +| AntiKillAuraService | KillAura | 多目标切换频率、Aimbot 角度一致性、极限距离攻击模式 | +| AntiReachService | Reach | 攻击距离验证、位置回溯检测 | +| AntiSpeedService | Speed | 水平移动速度异常分析 | +| AntiCriticalsService | Criticals | 零速度暴击、无跳跃暴击、暴击率统计异常 | +| AntiAutoCrystalService | AutoCrystal | 末影水晶放置/引爆速度、最优位置计算检测 | +| AntiAutoTotemService | AutoTotem | 图腾换装速度(毫秒级检测)、连续图腾使用模式 | +| AntiSurroundService | Surround | 四向方块放置速度、防御方块模式识别 | +| AntiAutoTrapService | AutoTrap | 目标玩家围笼构建速度、活塞陷阱自动化 | +| AntiAutoArmor | AutoArmor | 多槽位装甲切换速度、背包扫描模式 | +| AntiChestSwap | ChestSwap | 胸甲/鞘翅互换 tick 级检测 | +| AntiAutoLog | AutoLog | 受伤后立即断线模式、低血量脱战检测 | +| AntiHitboxes | Hitboxes | 边缘命中率、射线追踪距离分布分析 | +| AntiBowAimbot | BowAimbot | 移动目标命中率、弹道一致性、瞬发精准检测 | +| AntiVelocityService | Velocity | 击退幅度异常、抗击退检测 | +| AntiAutoClickerService | AutoClicker | CPS 统计、点击间隔熵值分析 | + +### 二、反作弊 -- 移动类(18 模块) + +| 模块名称 | 对应 Hack | 检测原理 | +|---------|----------|---------| +| AntiFlyDetectionService | Fly | 垂直/水平速度、悬空时间、移动模式分析 | +| AntiJesusService | Jesus | 水面/岩浆面移动验证 | +| AntiNoFallService | NoFall | 落地检测、摔落伤害验证 | +| AntiSpeedService | Speed | 水平移动速度异常分析 | +| AntiTimerService | Timer | 游戏 tick 间隔异常、移动速度频率分析 | +| AntiPhaseService | Phase | 方块剪切/穿越检测、固体方块穿透验证 | +| AntiBlinkService | Blink | 快速断连躲避伤害检测 | +| AntiSpiderService | Spider | 无攀爬方块贴墙移动、垂直墙面移动检测 | +| AntiStepService | Step | 无跳跃跨越完整方块检测 | +| AntiNoSlowService | NoSlow | 使用物品时移速检测(吃食物/拉弓/举盾) | +| AntiPacketFlyService | PacketFly | 数据包操控飞行、上下震荡模式、永不落地检测 | +| AntiAirJumpService | AirJump | 半空跳跃数据包检测、连续空中跳跃 | +| AntiLongJump | LongJump | 极端水平跳跃距离检测 | +| AntiAntiHunger | AntiHunger | 高活动量零饥饿消耗检测 | +| AntiFastFall | FastFall | 超终端速度下落检测 | +| AntiVClip | VClip | 瞬间垂直穿透方块检测(排除合法传送) | +| AntiElytraFlyService | ElytraFly | 鞘翅速度/高度操控检测 | +| AntiScaffoldService | Scaffold | 方块放置频率/角度/速度模式分析 | + +### 三、反作弊 -- 世界/玩家/杂物类(19 模块) + +| 模块名称 | 对应 Hack | 检测原理 | +|---------|----------|---------| +| AntiNukerService | Nuker | 挖矿速度/范围/模式识别 | +| AntiAutoMineService | AutoMine | 自动化采矿行为检测 | +| AntiSpeedMineService | SpeedMine | 加速挖掘(InstaMine/PacketMine)检测 | +| AntiFastBreakService | FastBreak | 方块破坏速度异常检测 | +| AntiFastUseService | FastUse | 物品使用加速检测 | +| AntiNoInteractService | NoInteract | 交互绕过检测 | +| AntiVeinMinerService | VeinMiner | 矿脉自动化挖掘模式检测 | +| AntiAutoTool | AutoTool | 即时工具切换检测 | +| AntiAutoFishService | AutoFish | 钓鱼行为时序/反应速度分析 | +| AntiChestStealService | ChestSteal | 开箱/取物速度模式识别 | +| AntiInventoryManipulationService | InventoryManipulation | 背包操作速度、非法槽位操作检测 | +| AntiBaritoneService | Baritone | 路径平滑度/行为重复率分析 | +| AntiXrayDetectionService | Xray | 钻石比率/直线挖掘/暗处精准检测 | +| AntiGriefDetectionService | Grief | 方块破坏率/TNT/纵火/偷箱检测 | +| AntiFakePlayer | FakePlayer | 假人实体检测 | +| AntiPistonAura | PistonAura | 活塞陷阱自动化检测 | +| AntiAnchor | Anchor | 洞穴锚点防御检测 | +| AntiStashFinder | StashFinder | 自动化储藏箱探测检测 | +| AntiDupeDetectionService | AntiDupe | 物品复制检测(堆叠异常/9种复制法) | + +### 四、服务器漏洞防护(12 模块) + +| 模块名称 | 防护对象 | +|---------|---------| +| AntiSignExploitService | 告示牌 NBT 漏洞(超长 JSON/无效组件/NBT 炸弹) | +| AntiBookBanService | 书与笔封禁漏洞(超大页码/超深 JSON 层级) | +| AntiResourcePackExploitService | 资源包漏洞(恶意 URL/超大文件/格式校验) | +| AntiTabCompleteCrashService | Tab 补全崩溃(长文本/深度嵌套补全限制) | +| AntiOfflineModeSpoofService | 离线 UUID 欺诈(正版 UUID 冲突/IP 关联验证) | +| CrashExploitProtectionService | 崩溃漏洞防护(超大包/NBT 炸弹/书与笔攻击) | +| CrashExploitSignatureDB | 崩溃漏洞签名数据库(12 种已知签名匹配) | +| LagMachineDetectionService | 卡服机检测(Observer 链/TNT 堆/红石密度) | +| ChunkLoadRateLimiter | 区块加载速率限制(WARN/LIMIT/BLOCK 三级响应) | +| EntityCountEnforcer | 实体数量强制执行(按区块/玩家/类型自动清理) | +| RedstoneUpdateLimiter | 红石更新频率限制(降频/冻结/指数退避) | +| PacketFloodProtectionService | 数据包洪水防护 | + +### 五、聊天与社交安全(5 模块) + +| 模块名称 | 防护对象 | +|---------|---------| +| ChatFloodProtectionService | 聊天洪水(频率/相似度/长度激增) | +| AntiAdvertisementService | 广告检测(IP/域名/群号正则匹配) | +| AntiPhishingLinkService | 钓鱼链接(可疑域名/短链接/SSL 证书校验) | +| AntiCommandAbuseService | 命令滥用(频率限制/敏感命令拦截/权限校验) | +| PlayerPrivacyService | 玩家隐私保护(IP 脱敏/坐标隐藏/日志匿名化) | + +### 六、网络安全(13 模块) + +| 模块名称 | 防护对象 | +|---------|---------| +| DDoSProtectionService | DDoS 攻击(SYN/UDP/ICMP/HTTP/慢速连接/放大攻击) | +| DDoSDefenseCoordinator | DDoS 多层防御协调 | +| ProtocolStateValidator | 协议状态机验证(HANDSHAKE/STATUS/LOGIN/PLAY) | +| BotFingerprintDetector | 机器人指纹检测(登录时序/命名模式/移动熵值) | +| NBTExploitPrevention | NBT 漏洞防护(深度/尺寸限制) | +| ConnectionHandshakeValidator | 连接握手验证(协议版本/hostname/Ping 洪水/端口扫描) | +| PortScanDetectionService | 端口扫描检测 | +| BruteForceProtectionService | 暴力破解防护(多时间窗口检测) | +| AntiVPNProxyService | VPN/代理检测(已知 VPN IP 库/托管 ASN 匹配) | +| DNSTunnelDetectionService | DNS 隧道检测(熵值/Base32 编码/可疑 TLD) | +| ReverseShellDetectionService | 反向 Shell 检测(50+ shell 模式匹配) | +| ProcessInjectionDetectionService | 进程注入检测 | +| ARPSpoofDetectionService | ARP 欺骗检测(MAC 变更/网关伪造) | + +### 七、主机与访问控制安全(6 模块) + +| 模块名称 | 防护对象 | +|---------|---------| +| FileIntegrityMonitorService | 文件完整性监控(Hash 基线/实时监控) | +| BackdoorPluginScannerService | 后门插件扫描(已知恶意类名/远程执行/隐藏命令) | +| ConfigTamperDetectionService | 配置文件篡改检测(ops/whitelist 实时监控) | +| OPPrivilegeMonitorService | OP 权限监控(权限变更/敏感命令执行审计) | +| AntiAltAccountService | 小号检测(IP 关联/行为相似度/登录模式) | +| AntiNameSpoofService | 名称冒充检测(管理员/知名玩家昵称伪造) | + +### 八、高级安全基础设施(28 模块) + +| 模块名称 | 功能描述 | +|---------|---------| +| PlayerSessionValidationService | 玩家会话验证(UUID 伪造/正版/离线检测) | +| PluginVerificationService | 插件完整性校验(Hash 对比/未授权修改) | +| BackupIntegrityService | 备份完整性校验(SHA-256/文件计数/大小对比) | +| ConnectionThrottleService | 连接速率限制(IP/时间窗口/递增延迟) | +| GeoBlockService | 地理 IP 封锁(按国家/地区拦截) | +| AntiSkinSpoofService | 皮肤伪造检测(模型数据异常/皮肤 URL 检测) | +| JwtAuthService | JWT 身份认证与令牌管理 | +| AntiBotDetectionService | 反机器人检测(名称/加入速率/IP 关联) | +| CSPEnforcementService | CSP 安全头强制执行(8 种响应头) | +| SSRFProtectionService | SSRF 防护(内网 IP/云元数据/协议限制) | +| XXEProtectionService | XXE 防护(实体注入/Billion Laughs 检测) | +| DatabaseFirewallService | 数据库防火墙(SQL 注入/联合查询/时间盲注) | +| DataLossPreventionService | 数据防泄漏(12 种敏感信息规则+自动脱敏) | +| MemoryProtectionService | JVM 内存保护(堆/GC/内存泄漏检测) | +| SecureFileDeletionService | 安全文件删除(多道覆写 DoD 标准) | +| ForensicsCollectorService | 取证收集(进程/网络/日志快照) | +| IncidentResponseService | 事件响应(5 种预定义响应剧本) | +| ThreatHuntingService | 威胁狩猎(10 种狩猎定义/5 个类别) | +| ComplianceScannerService | 合规扫描(7 类 20+ 检查项) | +| ExploitSignatureService | 漏洞签名检测(Log4Shell/SQLi/RCE 等 15 种) | +| SecurityOrchestrationService | 多层防御编排(本地封锁/边缘挑战/Minecraft 防御) | +| SecurityAutomationScheduler | 安全自动化调度(情报刷新/态势快照/规则同步) | +| HostEnforcementService | 主机层面强制执行 | +| HostIntrusionCountermeasureService | 主机入侵对抗 | +| IntrusionDetectionService | 网络入侵检测 | +| IntrusionPreventionSystem | 网络入侵防御 | +| WebApplicationFirewall | Web 应用防火墙 | +| ZeroTrustArchitectureService | 零信任架构 | + +### 九、网络与流量分析(10 模块) + +| 模块名称 | 功能描述 | +|---------|---------| +| NetworkMonitorService | 网络流量监控 | +| NetworkSnifferService | 网络数据包嗅探 | +| NetworkThreatFusionService | 多源威胁情报融合 | +| FlowAnalyzerService | 流量行为分析 | +| TrafficAnalysisService | 流量模式分析 | +| TrafficShapingService | 流量整形与 QoS | +| PacketInspectionService | 深度包检测 | +| ProtocolAnalysisService | 协议异常分析 | +| TokenBucketRateLimiter | 令牌桶速率限制原语 | +| FirewallService | 系统防火墙管理 | + +### 十、基础设施与运维安全(8 模块) + +| 模块名称 | 功能描述 | +|---------|---------| +| SIEMService | 安全信息与事件管理 | +| LogAnalysisService | 日志模式分析 | +| LogCorrelationService | 跨源日志关联 | +| ThreatIntelligenceService | 威胁情报聚合 | +| IPReputationService | IP 信誉数据库查询 | +| SSLTLSCertificateService | SSL/TLS 证书管理 | +| SecurityBaselineHardeningService | 安全基线加固 | +| ContainerSecurityService | 容器运行时安全 | + +### 十一、ML/AI 行为分析(4 模块) + +| 模块名称 | 功能描述 | +|---------|---------| +| BehavioralProfilingEngine | 玩家行为画像引擎(基于统计特征的行为基线建模) | +| CombatPatternRecognizer | 战斗模式识别器(异常战斗序列检测) | +| MovementPatternAnalyzer | 移动模式分析器(轨迹异常、路径熵值) | +| ThreatScoreAggregator | 威胁评分聚合器(多维度威胁评分融合与升级) | + +--- + +## 部署指南 + +### 模式一:Plugin 内嵌模式(推荐) + +ServerGuard 以 Paper 插件形式直接运行在 Minecraft 服务器进程内部,零网络延迟,最高实时性能。 + +**前置条件:** +- Minecraft PaperMC 1.21.1 服务器已安装 +- Java 21 运行时 +- ServerGuard 引擎 JAR 已编译 + +**部署步骤:** + +1. **编译插件** + ```bash + cd /opt/AluerIII + ./apache-maven-3.9.6/bin/mvn package -DskipTests + ``` + +2. **安装插件到 Minecraft** + ```bash + cp target/serverguard-4.0.0.jar /opt/minecraft/plugins/AluerServerGuard.jar + ``` + +3. **创建插件配置文件** `plugins/AluerServerGuard/config.yml`: + ```yaml + server-url: ws://localhost:8080/agent + ``` + +4. **启动 ServerGuard 引擎**(必须先于 Minecraft 服务器启动) + ```bash + java -jar target/serverguard-4.0.0.jar + ``` + +5. **启动 Minecraft 服务器** + ```bash + cd /opt/minecraft + java -Xms4G -Xmx4G -jar paper-1.21.11.jar + ``` + +启动后,AluerPlugin 将自动通过 WebSocket 连接到 ServerGuard 引擎并向其推送 Bukkit 事件数据。 + +### 模式二:External 外部监控模式 + +ServerGuard 作为独立进程运行,通过 RCON 和日志监控进行外部防护。适用于不想安装插件的场景。 + +**部署步骤:** + +1. **编译** + ```bash + ./apache-maven-3.9.6/bin/mvn package -DskipTests + ``` + +2. **配置 `application.yml`** + ```yaml + serverguard: + mode: external + minecraft: + working-dir: /opt/minecraft + rcon: + enabled: true + host: localhost + port: 25575 + password: "your_rcon_password_here" + process-name: paper-1.21.11.jar + ``` + +3. **在 Minecraft `server.properties` 中启用 RCON** + ```properties + enable-rcon=true + rcon.port=25575 + rcon.password=your_rcon_password_here + ``` + +4. **启动 ServerGuard** + ```bash + java -jar target/serverguard-4.0.0.jar + ``` + +--- + +## 配置参考 + +### 核心配置(serverguard.*) + +```yaml +serverguard: + mode: ${SERVERGUARD_MODE:external} # plugin 或 external + + minecraft: + service-name: minecraft + process-name: paper-1.21.11.jar + jar-file: paper-1.21.11.jar + working-dir: /opt/minecraft + java-opts: -Xms4G -Xmx4G + check-interval-seconds: 5 + rcon: + enabled: true + host: localhost + port: 25575 + password: ${RCON_PASSWORD:} + + monitor: + tps-threshold: 15 # TPS 低于此值触发告警 + cpu-threshold: 80.0 # CPU 使用率超过此值触发告警(%) + memory-threshold: 85.0 # 内存使用率超过此值触发告警(%) + connection-threshold: 50 # 同时连接数超过此值触发告警 + log-watch-lines: 100 # 日志监控行数 + log-path: /opt/minecraft/logs/latest.log + + alert: + enabled: true + email: + smtp-host: smtp.qq.com + smtp-port: 587 + username: ${ALUER_ALERT_SMTP_USERNAME:} + password: ${ALUER_ALERT_SMTP_PASSWORD:} + to: + - ${ALUER_ALERT_EMAIL_PRIMARY:} + - ${ALUER_ALERT_EMAIL_SECONDARY:} + rate-limit: + per-type-seconds: 300 # 同类型告警最小间隔(秒) + max-emails-per-minute: 10 # 每分钟最大邮件数 ``` -自适应权重通过指数移动平均动态调整: +### AI 配置(serverguard.ai.*) -``` -target_weight = baseline_weight + (module_pressure ≥ 80 ? 0.18 : module_pressure ≥ 55 ? 0.08 : 0) -active_weight = current × 0.82 + target × 0.18 -active_weight = clamp(active_weight, 0.72, 1.45) +```yaml + ai: + enabled: true + use-isolation-forest: true # 启用隔离森林异常检测 + use-prediction: true # 启用时间序列预测 + sliding-window-size: 100 # 分析滑动窗口大小 + anomaly-threshold: 0.7 # 异常判定阈值(0-1) + prediction-horizon-minutes: 60 # 预测时间范围(分钟) + deepseek: + enabled: true + api-key: ${DEEPSEEK_API_KEY:} + base-url: ${DEEPSEEK_BASE_URL:https://api.deepseek.com} + model: ${DEEPSEEK_MODEL:deepseek-chat} + max-tokens: 1000 + temperature: 0.35 # 分析稳定性(0=精确,1=创造性) + auto-analyze-alerts: true # 自动分析告警 + analysis-interval-seconds: 45 # 分析间隔(秒) + auto-execute: + enabled: true + ban-ip: true # 允许自动封禁 IP + kill-entity: true # 允许自动清除实体 + clear-lag: true # 允许自动清理延迟 + set-spawn-rate: true # 允许自动调整生成率 + kick-player: true # 允许自动踢出玩家 + whitelist: true # 允许自动启用白名单 + min-confidence: 88 # 自动执行的最低置信度(%) ``` -EchoGrid (攻击者记忆)衰减公式: +### 安全防御配置(serverguard.security.*) -``` -cell.pressure = cell.pressure × 0.55 + pulse.heat × 0.75 -// 超过 retention 时间未更新的 cell 自动清除 +```yaml + security: + enabled: true + auto-ban-vpn: true + check-on-login: true + max-connections-per-ip: 3 # 每 IP 最大连接数 + block-common-exploits: true + log-all-commands: true + + minecraft-defense: + enabled: true + game-tcp-port: 25565 + query-udp-port: 25565 + rcon-tcp-port: 25575 + status-ping-threshold: 25 # Status Ping 洪水阈值 + login-burst-threshold: 12 # 登录突发阈值 + bot-swarm-threshold: 15 # 机器人集群阈值 + query-flood-threshold: 30 # Query 洪水阈值 + rcon-brute-force-threshold: 5 # RCON 暴力破解阈值 + compression-payload-threshold: 8192 # 压缩载荷上限 + + ddos-defense: + enabled: true + syn-flood-threshold: 100 + udp-flood-threshold: 200 + icmp-flood-threshold: 100 + http-flood-threshold: 150 + slow-connection-threshold: 150 + amplification-threshold: 20 + minecraft-status-threshold: 20 + minecraft-login-threshold: 10 + minecraft-rcon-threshold: 5 + minecraft-query-threshold: 25 + minecraft-bot-swarm-threshold: 12 + + anti-intrusion: + enabled: true + monitor-commands: true + monitor-processes: true + monitor-files: true + monitor-plugins: true + monitor-systemd: true + monitor-rcon: true + file-integrity: + enabled: true + max-depth: 5 + monitored-paths: + - /opt/minecraft/plugins + - /opt/minecraft/server.properties + - /opt/minecraft/paper-1.21.11.jar + - /opt/minecraft/start.sh + - /etc/systemd/system/minecraft.service + + host-enforcement: + enabled: true + dry-run: true # 干燥运行模式(不实际执行封锁) + preferred-backend: auto # 后端选择:auto/iptables/nftables/firewalld + default-block-minutes: 60 # 默认封锁时间(分钟) + default-rate-limit-per-minute: 120 # 默认每分钟限速 + mirror-to-cloud-edge: true # 同步到云端边缘 + + cloud-edge: + enabled: false + dry-run: true + provider: cloudflare + zone-id: ${ALUER_CLOUDFLARE_ZONE_ID:} + api-key: ${ALUER_CLOUDFLARE_API_KEY:} + api-email: ${ALUER_CLOUDFLARE_EMAIL:} + default-block-mode: block + default-challenge-mode: challenge + enable-under-attack-on-critical: true + + orchestration: + enabled: true + allow-local-block: true + allow-edge-challenge: true + allow-minecraft-defense: true + notify-on-critical: true + + automation: + enabled: true + feed-refresh-minutes: 15 # 威胁情报刷新间隔 + posture-snapshot-minutes: 5 # 安全态势快照间隔 + integrity-rescan-minutes: 30 # 完整性重新扫描间隔 + rule-sync-minutes: 10 # 规则同步间隔 + incident-retention-minutes: 120 # 事件保留时间 + + autonomy: + enabled: true + deepseek-dominant: true # DeepSeek 主导决策 + quiet-console: true # 静默控制台 + loop-interval-seconds: 45 # 自主循环间隔 + min-risk-score-for-action: 70 # 最低行动风险分数 + critical-risk-score: 90 # 严重风险分数 + workflow-cooldown-seconds: 180 # 工作流冷却时间 + max-actions-per-hour: 12 # 每小时最大行动次数 + require-second-signal-for-containment: true # 需要二次信号确认封锁 + + shield: + enabled: true + auto-mode: true + auto-enable-under-attack: true + heat-trigger: 78 # 热量触发阈值 + resonance-trigger: 72 # 共振触发阈值 + threat-score-trigger: 85 # 威胁分数触发阈值 + edge-challenge-offender-limit: 6 # 边缘挑战违规者上限 + shelter-rate-limit-per-minute: 45 # 庇护所每分钟限速 + attacker-notice-enabled: true + deterrence-message: "Your source has been identified, recorded, and isolated by Aluer." + + kernel: + enabled: true + pulse-interval-seconds: 30 # 脉冲间隔 + pulse-history-size: 180 # 脉冲历史大小 + journal-size: 300 # 日志大小 + echo-retention-minutes: 180 # 回响保留时间 + adaptive-weights: true # 自适应权重 + directive-heat-threshold: 60 # 指令热量阈值 + lockdown-heat-threshold: 82 # 封锁热量阈值 + + task-bus: + enabled: true + auto-dispatch: true + dispatch-interval-seconds: 10 + queue-limit: 200 + history-limit: 300 + + self-healing: + enabled: true + dry-run: true # 干燥运行模式 + loop-interval-seconds: 45 + auto-backup-before-recovery: true # 恢复前自动备份 + auto-whitelist-on-swarm: true # 集群攻击时自动白名单 + allow-soft-restart: true # 允许软重启 + tps-emergency-threshold: 12 # TPS 紧急阈值 + cpu-emergency-threshold: 92.0 # CPU 紧急阈值(%) + memory-emergency-threshold: 95.0 # 内存紧急阈值(%) + max-recovery-actions-per-hour: 8 # 每小时最大恢复行动 ``` -### 3. 数据流全景 +### SuperEvolution 模块开关(serverguard.security.super-evolution.*) +```yaml + super-evolution: + # === V4.0 高级扩展安全模块 === + jwt-auth: true # JWT 身份认证与令牌管理 + brute-force: true # 暴力破解防护(多时间窗口检测) + anti-bot: true # 反机器人检测 + reverse-shell: true # 反向 Shell 检测(50+ 模式匹配) + arp-spoof: true # ARP 欺骗检测 + dns-tunnel: true # DNS 隧道检测(熵值/Base32编码/可疑TLD) + exploit-signature: true # 漏洞签名检测(Log4Shell/SQLi/RCE等15种) + ssrf: true # SSRF 防护 + xxe: true # XXE 防护 + csp: true # CSP 安全头强制执行 + database-firewall: true # 数据库防火墙 + dlp: true # 数据防泄漏(12种敏感信息规则) + memory-protection: true # JVM 内存保护 + process-injection: true # 进程注入检测 + secure-delete: true # 安全文件删除 + forensics: true # 取证收集 + incident-response: true # 事件响应(5种预定义剧本) + threat-hunting: true # 威胁狩猎(10种狩猎定义) + compliance: true # 合规扫描(7类20+检查项) + anti-grief: true # 反破坏检测 + # === Minecraft 专属防护 === + anti-xray: true # X-ray 透视检测 + anti-fly: true # 飞行外挂检测 + anti-dupe: true # 物品复制检测(9种复制法) + crash-exploit: true # 崩溃漏洞防护 + lag-machine: true # 卡服机检测 + # === V4.0 新增模块 === + geo-block: true # 地理 IP 封锁 + session-validation: true # 玩家会话验证 + plugin-verification: true # 插件完整性校验 + connection-throttle: true # 连接速率限制 + backup-integrity: true # 备份完整性校验 + anti-skin-spoof: true # 皮肤伪造检测 + # === V4.0 反作弊扩展模块 === + anti-kill-aura: true # 杀戮光环检测 + anti-reach: true # 超距攻击检测 + anti-speed: true # 水平速度检测 + anti-jesus: true # 水上行走检测 + anti-no-fall: true # 无摔落伤害检测 + anti-scaffold: true # 自动搭路检测 + anti-timer: true # 游戏加速检测 + anti-velocity: true # 击退修改检测 + anti-phase: true # 穿墙检测 + anti-blink: true # 闪烁检测 + anti-fast-break: true # 快速破坏检测 + anti-elytra-fly: true # 鞘翅飞行检测 + # === V4.0 玩家行为安全模块 === + anti-nuker: true # 快速破坏检测 + anti-auto-clicker: true # 自动点击检测 + anti-chest-steal: true # 自动偷箱检测 + anti-auto-fish: true # 自动钓鱼检测 + anti-inventory-manipulation: true # 背包操作检测 + anti-baritone: true # AI 寻路机器人检测 + # === V4.0 服务器保护模块 === + packet-flood-protection: true # 数据包洪水防护 + anti-sign-exploit: true # 告示牌漏洞防护 + anti-book-ban: true # 书与笔封禁防护 + anti-resource-pack-exploit: true # 资源包漏洞防护 + anti-tab-complete-crash: true # Tab 补全崩溃防护 + anti-offline-mode-spoof: true # 离线 UUID 欺诈防护 + # === V4.0 访问控制模块 === + op-privilege-monitor: true # OP 权限监控 + config-tamper-detection: true # 配置文件篡改检测 + backdoor-plugin-scanner: true # 后门插件扫描 + anti-vpn-proxy: true # VPN 代理检测 + anti-alt-account: true # 小号检测 + anti-name-spoof: true # 名称冒充检测 + # === V4.0 聊天社交安全模块 === + chat-flood-protection: true # 聊天洪水防护 + anti-advertisement: true # 广告检测 + anti-phishing-link: true # 钓鱼链接检测 + anti-command-abuse: true # 命令滥用检测 + player-privacy: true # 玩家隐私保护 + # === V5.0 服务器保护扩展 === + chunk-load-rate-limiter: true # 区块加载速率限制 + entity-count-enforcer: true # 实体数量强制执行 + redstone-update-limiter: true # 红石更新频率限制 + crash-exploit-signature-db: true # 崩溃漏洞签名数据库 + # === V4.0 网络协议安全模块 === + protocol-validator: true # 协议状态机验证 + token-bucket-rate-limiter: true # 令牌桶速率限制 + bot-fingerprint: true # 机器人行为指纹检测 + nbt-exploit-prevention: true # NBT 漏洞防护 + handshake-validator: true # 连接握手验证 + # === V5.1 反作弊战斗模块(Meteor Client 对抗) === + anti-criticals: true # 自动暴击检测 + anti-auto-totem: true # 自动不死图腾检测 + anti-surround: true # 自动包围检测 + anti-auto-trap: true # 自动困笼检测 + anti-auto-crystal: true # 自动末影水晶检测 + anti-auto-armor: true # 自动盔甲检测 + anti-chest-swap: true # 快速胸甲切换检测 + anti-auto-log: true # 自动断线检测 + anti-hitboxes: true # 扩大碰撞箱检测 + anti-bow-aimbot: true # 弓自瞄检测 + # === V5.2 反作弊移动模块(Meteor Client 移动类对抗) === + anti-no-slow: true # 无减速检测 + anti-spider: true # 爬墙检测 + anti-step: true # 自动跨步检测 + anti-packet-fly: true # 数据包飞行检测 + anti-air-jump: true # 空中跳跃检测 + anti-long-jump: true # 远跳检测 + anti-anti-hunger: true # 反饥饿检测 + anti-fast-fall: true # 快速坠落检测 + anti-vclip: true # 垂直穿墙检测 + # === V5.3 反作弊世界/玩家/杂物模块(Meteor Client 对抗) === + anti-speed-mine: true # 加速挖掘检测 + anti-fast-use: true # 加速物品使用检测 + anti-no-interact: true # 交互绕过检测 + anti-auto-mine: true # 自动挖矿检测 + anti-vein-miner: true # 矿脉自动挖掘检测 + anti-auto-tool: true # 自动工具切换检测 + anti-fake-player: true # 假人实体检测 + anti-piston-aura: true # 活塞陷阱自动化检测 + anti-anchor: true # 洞穴锚点检测 + anti-stash-finder: true # 自动储藏箱探测 ``` - ┌──────────────┐ - │ Minecraft │ - │ PaperMC │ - │ (RCON 25575) │ - └──┬───────┬──┘ - │ │ - RCON 指令 │ │ latest.log - (ban-ip / │ │ /proc 指标 - kick / │ │ netstat - whitelist) │ │ - │ │ - ┌────────────────────┴───────┴──────────────────────┐ - │ Aluer ServerGuard │ - │ │ - │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ - │ │ Monitor │ │ Security │ │ AI │ │ - │ │ Process │ │ DDoS/IDS │ │ DeepSeek │ │ - │ │ Resource │ │ WAF/Honey│ │ Anomaly │ │ - │ │ Connect │ │ ZeroTrust│ │ Predict │ │ - │ │ Log │ │ 85+ svc │ │ Adaptive │ │ - │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ - │ │ │ │ │ - │ └─────────┬───┴─────────────┘ │ - │ │ │ - │ ┌────────────┴────────────┐ │ - │ │ Kernel + Sovereign │ │ - │ │ 信号融合 + 指令产出 │ │ - │ └────────────┬────────────┘ │ - │ │ │ - │ ┌────────────┴────────────┐ │ - │ │ AutoExecutor / RCON │ │ - │ │ 指令执行 + 操作记录 │ │ - │ └────────────────────────┘ │ - │ │ - │ ┌────────────────────────┐ │ - │ │ Web Dashboard :8080 │ ← 管理员浏览器 │ - │ │ Spring Shell Terminal │ ← 管理员终端 │ - │ └────────────────────────┘ │ - └────────────────────────────────────────────────────┘ - │ - Cloudflare API - (边缘挑战 / 封禁 / Under Attack) + +### 其他配置节 + +```yaml + dashboard: + enabled: true + title: "Aluer Nebula Console" + subtitle: "PaperMC defense, recovery, and remote operations fabric" + refresh-interval-seconds: 6 + compact-terminal: true + ssh-gateway: + enabled: true + session-timeout-minutes: 30 + max-sessions: 6 + command-timeout-seconds: 25 + strict-host-key-checking: false + allow-private-key-paste: true + require-engine-handshake: true + handshake-ttl-seconds: 30 + + announcement: + enabled: false + interval-seconds: 300 + messages: + - "Welcome to the server!" + + afk: + enabled: false + afk-timeout-minutes: 5 + max-afk-minutes: 30 + teleport-to-afk-zone: false + afk-zone: "0,100,0" + auto-logout: false + + chat-filter: + enabled: false + block-ip: true + block-profanity: true + block-advertising: true + block-spam: true + block-illegal: true + spam-threshold: 5 + spam-window-seconds: 10 + mute-on-violation: true + mute-duration-minutes: 5 + kick-on-repeat: true + max-violations-before-kick: 3 + + backup: + enabled: false + backup-dir: /opt/minecraft/backups + world-dir: /opt/minecraft/world + plugin-dir: /opt/minecraft/plugins + config-dir: /opt/minecraft + interval-hours: 24 + max-backups: 7 + compress: true + backup-plugins: true + backup-config: false + notify-on-complete: true + + schedule: + enabled: true + daily-restart: true + restart-time: "04:00" + save-before-restart: true + announce-restart: true + announce-message: "Server will restart in {minutes} minutes" + weekly-backup: true + backup-day: sunday + backup-time: "03:00" + clear-lag-daily: true + clear-lag-time: "02:00" ``` --- -## 🚀 快速开始 +## WebSocket 通信协议 + +### 消息格式 + +所有消息均为单行 JSON,通过 WebSocket 文本帧传输。 + +**Agent → Server 消息示例(事件上报):** + +```json +{ + "type": "EVENT", + "agentId": "agent-survival-01", + "timestamp": 1715000000000, + "payload": { + "eventType": "PLAYER_MOVE", + "playerName": "Steve", + "x": 100.5, + "y": 64.0, + "z": 200.3, + "yaw": 45.0, + "pitch": 0.0 + } +} +``` + +**Agent → Server 心跳消息:** + +```json +{ + "type": "HEARTBEAT", + "agentId": "agent-survival-01", + "timestamp": 1715000005000, + "payload": { + "status": "alive" + } +} +``` + +**Server → Agent 命令消息:** + +```json +{ + "type": "COMMAND", + "requestId": "550e8400-e29b-41d4-a716-446655440000", + "timestamp": 1715000001000, + "payload": { + "command": "KICK", + "target": "Hacker123", + "reason": "KillAura detected - confidence 94%" + } +} +``` + +### 事件类型完整列表 + +| 事件类型常量 | 值 | 说明 | +|-------------|-----|------| +| EVENT_PLAYER_JOIN | PLAYER_JOIN | 玩家加入服务器 | +| EVENT_PLAYER_QUIT | PLAYER_QUIT | 玩家退出服务器 | +| EVENT_PLAYER_MOVE | PLAYER_MOVE | 玩家移动(含坐标 x/y/z 和角度 yaw/pitch) | +| EVENT_PLAYER_TELEPORT | PLAYER_TELEPORT | 玩家传送 | +| EVENT_PLAYER_CHAT | PLAYER_CHAT | 聊天消息 | +| EVENT_PLAYER_COMMAND | PLAYER_COMMAND | 命令执行 | +| EVENT_PLAYER_DAMAGE | PLAYER_DAMAGE | 玩家受伤 | +| EVENT_COMBAT_ATTACK | COMBAT_ATTACK | 攻击事件(含攻击者/目标/伤害量) | +| EVENT_COMBAT_DEATH | COMBAT_DEATH | 死亡事件 | +| EVENT_BLOCK_BREAK | BLOCK_BREAK | 方块破坏(含方块类型/坐标/工具) | +| EVENT_BLOCK_PLACE | BLOCK_PLACE | 方块放置 | +| EVENT_INVENTORY_CLICK | INVENTORY_CLICK | 背包操作(含槽位/物品类型) | +| EVENT_ENTITY_SPAWN | ENTITY_SPAWN | 实体生成 | +| EVENT_CHUNK_LOAD | CHUNK_LOAD | 区块加载 | + +### 命令类型完整列表 + +| 命令常量 | 值 | 说明 | +|---------|-----|------| +| CMD_BAN_IP | BAN_IP | 封禁 IP 地址 | +| CMD_BAN_PLAYER | BAN_PLAYER | 封禁玩家账号 | +| CMD_KICK | KICK | 踢出玩家 | +| CMD_CLEAR_LAG | CLEAR_LAG | 清理所有非玩家实体 | +| CMD_SET_SPAWN_RATE | SET_SPAWN_RATE | 动态调整生物生成率 | +| CMD_ENABLE_WHITELIST | ENABLE_WHITELIST | 启用服务器白名单 | +| CMD_DISABLE_WHITELIST | DISABLE_WHITELIST | 关闭服务器白名单 | +| CMD_BROADCAST | BROADCAST | 向全服广播消息 | +| CMD_SAVE_ALL | SAVE_ALL | 强制保存所有世界 | +| CMD_EXECUTE | EXECUTE | 执行任意控制台命令 | + +--- + +## 告警类型完整列表 + +系统支持 75 种告警类型,定义在 `AlertType.java` 枚举中: + +**系统监控(8):** +PROCESS_DEAD, TPS_LOW, CPU_HIGH, MEM_HIGH, CONNECTION_FLOOD, LOG_ATTACK, BACKUP_FAILED, AI_ANOMALY + +**V4.0 反作弊(10):** +SECURITY_KILL_AURA, SECURITY_REACH, SECURITY_SPEED, SECURITY_JESUS, SECURITY_NOFALL, SECURITY_SCAFFOLD, SECURITY_NUKER, SECURITY_AUTO_CLICKER, SECURITY_AUTO_FISH, SECURITY_FLY + +**V5.0 反作弊(6):** +SECURITY_TIMER, SECURITY_VELOCITY, SECURITY_PHASE, SECURITY_BLINK, SECURITY_FAST_BREAK, SECURITY_ELYTRA_FLY + +**V5.1 战斗(10):** +SECURITY_CRITICALS, SECURITY_AUTO_TOTEM, SECURITY_SURROUND, SECURITY_AUTO_TRAP, SECURITY_AUTO_CRYSTAL, SECURITY_AUTO_ARMOR, SECURITY_CHEST_SWAP, SECURITY_AUTO_LOG, SECURITY_HITBOXES, SECURITY_BOW_AIMBOT + +**V5.2 移动(9):** +SECURITY_NO_SLOW, SECURITY_SPIDER, SECURITY_STEP, SECURITY_PACKET_FLY, SECURITY_AIR_JUMP, SECURITY_LONG_JUMP, SECURITY_ANTI_HUNGER, SECURITY_FAST_FALL, SECURITY_VCLIP + +**V5.3 世界/杂物(10):** +SECURITY_SPEED_MINE, SECURITY_FAST_USE, SECURITY_NO_INTERACT, SECURITY_AUTO_MINE, SECURITY_VEIN_MINER, SECURITY_AUTO_TOOL, SECURITY_FAKE_PLAYER, SECURITY_PISTON_AURA, SECURITY_ANCHOR, SECURITY_STASH_FINDER + +**玩家行为(6):** +SECURITY_CHEST_STEAL, SECURITY_INVENTORY_MANIPULATION, SECURITY_GRIEF, SECURITY_ALT_ACCOUNT, SECURITY_BARITONE, SECURITY_XRAY + +**服务器保护(9):** +SECURITY_SIGN_EXPLOIT, SECURITY_BOOK_BAN, SECURITY_RESOURCE_PACK_EXPLOIT, SECURITY_TAB_COMPLETE_CRASH, SECURITY_OFFLINE_MODE_SPOOF, SECURITY_CHUNK_RATE, SECURITY_ENTITY_LIMIT, SECURITY_REDSTONE_LAG, SECURITY_CRASH_EXPLOIT + +**聊天安全(4):** +CHAT_FLOOD, CHAT_ADVERTISEMENT, CHAT_PHISHING, COMMAND_ABUSE + +**网络安全(9):** +SECURITY_DDOS, SECURITY_PORT_SCAN, SECURITY_BRUTE_FORCE, SECURITY_VPN_PROXY, SECURITY_DNS_TUNNEL, SECURITY_PROTOCOL_VIOLATION, SECURITY_BOT_FINGERPRINT, SECURITY_NBT_EXPLOIT, SECURITY_HANDSHAKE_ANOMALY + +**主机安全(5):** +SECURITY_REVERSE_SHELL, SECURITY_PROCESS_INJECTION, SECURITY_FILE_TAMPER, SECURITY_BACKDOOR_PLUGIN, SECURITY_CONFIG_TAMPER + +**ML 分析(4):** +ML_BEHAVIOR_ANOMALY, ML_THREAT_ESCALATION, ML_MOVEMENT_PATTERN, ML_COMBAT_PATTERN + +**通用(1):** +SECURITY_OTHER + +--- + +## 测试指南 + +### 运行全量测试 + +```bash +cd /opt/AluerIII +./apache-maven-3.9.6/bin/mvn test +``` + +### 测试规范 + +本项目遵循严格的测试纪律: +- **打靶试验**:测试必须模拟真实 Minecraft 服务器环境 +- **生产对齐**:测试数据和行为必须与实际生产环境对齐 +- **双构造函数模式**:每个 Service 类同时提供无参构造函数(用于测试)和 @Autowired 构造函数(用于生产注入) +- **静态工厂方法**:检测结果使用 `clean()`, `blocked()`, `flagged()` 静态工厂方法构建 +- **全量验证**:修改前后必须跑全量测试,任何失败必须立即修复 + +### 构建命令 + +```bash +# 编译项目 +./apache-maven-3.9.6/bin/mvn compile + +# 运行全量测试 +./apache-maven-3.9.6/bin/mvn test + +# 打包(跳过测试,用于快速部署) +./apache-maven-3.9.6/bin/mvn package -DskipTests + +# 清理构建产物 +./apache-maven-3.9.6/bin/mvn clean +``` + +--- + +## 项目结构 + +``` +AluerIII/ +├── pom.xml # Maven 构建配置 +├── application.yml # Spring Boot 配置(316 行) +├── CLAUDE.md # 开发规范文档 +├── README.md # 项目说明(中文) +├── README_EN.md # 项目说明(English) +├── docs/ +│ ├── DEVELOPER.md # 开发者参考手册 +│ ├── PROJECT_SUMMARY.md # 项目总览与模块拆解 +│ └── USER_MANUAL.md # 用户手册 +├── apache-maven-3.9.6/ # 捆绑的 Maven 3.9.6 +├── src/ +│ ├── main/java/com/aluer/ +│ │ ├── ServerGuardApplication.java # Spring Boot 主入口 +│ │ ├── config/ +│ │ │ └── ServerGuardConfig.java # 完整配置类(1273 行,含 SuperEvolutionConfig) +│ │ ├── model/ +│ │ │ └── AlertType.java # 告警类型枚举(75 种告警类型) +│ │ ├── agent/ +│ │ │ └── AgentMessage.java # Agent 通信协议定义 +│ │ ├── security/ # 安全模块(123 个 Java 文件) +│ │ │ ├── AntiKillAuraService.java +│ │ │ ├── AntiReachService.java +│ │ │ ├── AntiAutoCrystalService.java +│ │ │ ├── ... (120+ 更多) +│ │ │ └── ZeroTrustArchitectureService.java +│ │ ├── ml/ # ML 模块(4 个文件) +│ │ │ ├── BehavioralProfilingEngine.java +│ │ │ ├── CombatPatternRecognizer.java +│ │ │ ├── MovementPatternAnalyzer.java +│ │ │ └── ThreatScoreAggregator.java +│ │ ├── plugin/ # Paper 插件实现 +│ │ │ ├── AluerPlugin.java # 插件主入口(JavaPlugin) +│ │ │ ├── AluerCommandExecutor.java # 命令注册器 +│ │ │ ├── bridge/ +│ │ │ │ ├── AgentWebSocketClient.java # WebSocket 客户端 +│ │ │ │ ├── DataBridge.java # 数据格式转换桥接 +│ │ │ │ └── InternalCommandExecutor.java # Bukkit API 命令执行器 +│ │ │ └── listener/ # Bukkit 事件监听器(9 个) +│ │ │ ├── BlockEventListener.java # 方块事件(破坏/放置) +│ │ │ ├── ChatEventListener.java # 聊天/社交事件 +│ │ │ ├── CombatEventListener.java # 战斗事件(攻击/死亡) +│ │ │ ├── CommandEventListener.java # 命令执行事件 +│ │ │ ├── EntityEventListener.java # 实体生成/销毁事件 +│ │ │ ├── InventoryEventListener.java # 背包/容器事件 +│ │ │ ├── PacketEventListener.java # 原始数据包事件 +│ │ │ ├── PlayerEventListener.java # 玩家加入/退出/移动事件 +│ │ │ └── WorldEventListener.java # 世界/区块事件 +│ │ ├── controller/ +│ │ │ └── TestController.java # 测试控制器 +│ │ └── websocket/ # WebSocket 服务端 +│ └── main/resources/ +│ └── application.yml # 默认配置文件 +└── src/test/ # 测试代码目录 +``` + +--- + +## 开发指南 + +### 快速开始 + +```bash +# 1. 克隆项目 +git clone +cd AluerIII + +# 2. 编译项目 +./apache-maven-3.9.6/bin/mvn compile + +# 3. 运行全量测试 +./apache-maven-3.9.6/bin/mvn test + +# 4. 打包部署 +./apache-maven-3.9.6/bin/mvn package -DskipTests +``` ### 环境要求 | 依赖 | 版本 | 说明 | |------|------|------| -| JDK | 17+ | 编译和运行 | -| Maven | 3.9+(内置) | `apache-maven-3.9.6/` 已打包在仓库中 | -| OS | Ubuntu / Debian | 生产环境推荐,其他 Linux 也可运行但部分安全模块依赖 iptables/ufw | -| Memory | 2 GB+ 可用 | JVM 堆 + Minecraft 服务端本身的内存占用之外 | -| Disk | 10 GB+ | 日志 + 备份 + jar 包 | -| Minecraft | PaperMC 1.21+ | 需开启 RCON(`server.properties` 中 `enable-rcon=true`) | -| DeepSeek | API Key | AI 决策和自然语言问答必需 | -| Node.js | 18+(仅开发前端时需要) | 生产部署使用预构建的静态资源 | +| Java JDK | 21+ | 编译和运行环境 | +| Maven | 3.9.6 | 项目自带捆绑版本 | +| PaperMC | 1.21.1 | Plugin 模式下的 Minecraft 服务端 | -### 本地构建 +### 开发规范 -```bash -# 1. 克隆仓库 -git clone https://github.com/ZpjDev/Aluer.git -cd serverguard - -# 2. 使用项目内置的 Maven 构建 -./apache-maven-3.9.6/bin/mvn clean package -DskipTests - -# 3. 产物位置 -ls -lh target/serverguard.jar -``` - -构建过程同时会通过 Vite 编译前端 React 应用,将产物输出到 `src/main/resources/static/`,最终嵌入 jar 包。 - -### 环境变量配置 - -**最小可运行配置**(仅需 3 个环境变量): - -```bash -# 必须:DeepSeek API Key(从 https://platform.deepseek.com 获取) -export DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - -# 必须:RCON 密码(与 Minecraft server.properties 中 rcon.password 一致) -export RCON_PASSWORD=your-strong-rcon-password -``` - -**完整生产环境配置**: - -```bash -# ──── 核心凭证 ──── -export DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -export DEEPSEEK_BASE_URL=https://api.deepseek.com # 可选,默认值 -export DEEPSEEK_MODEL=deepseek-chat # 可选 -export RCON_PASSWORD=your-strong-rcon-password - -# ──── 邮件告警(QQ 邮箱示例) ──── -export ALUER_ALERT_SMTP_USERNAME=your-email@qq.com -export ALUER_ALERT_SMTP_PASSWORD=your-smtp-auth-code # QQ 邮箱需使用授权码 -export ALUER_ALERT_EMAIL_PRIMARY=admin@example.com -export ALUER_ALERT_EMAIL_SECONDARY=backup@example.com # 可选 - -# ──── Cloudflare 边缘防护(可选) ──── -export ALUER_CLOUDFLARE_ZONE_ID=your-zone-id -export ALUER_CLOUDFLARE_API_KEY=your-api-key -export ALUER_CLOUDFLARE_EMAIL=your-cloudflare-email -``` - -> **安全提示**:不要将 API Key 和密码硬编码在 `application.yml` 中。所有敏感配置项都使用 `${VAR_NAME:}` 占位符语法引用环境变量,未设置时使用空字符串作为默认值。 - -### 首次启动 - -```bash -# 前台启动(可看到 Spring Shell 交互终端) -java -jar target/serverguard.jar - -# 后台启动(使用提供的脚本) -./start.sh - -# 使用 systemd(推荐生产环境) -sudo systemctl start serverguard -``` - -启动成功后会显示 Spring Shell 终端: - -``` -╔══════════════════════════════════════════════════╗ -║ 欢迎使用 Aluer 服务器安全防护系统 ║ -╠══════════════════════════════════════════════════╣ -║ 输入 help 查看可用命令 ║ -║ 输入 ai <问题> 使用 AI 智能助手 ║ -╚══════════════════════════════════════════════════╝ -aluer> -``` - -验证一切正常: - -```bash -# 测试 API -curl http://localhost:8080/api/status - -# 预期响应 -{"status":"running","timestamp":1746883200000} - -# 访问 Web 控制台 -curl http://localhost:8080/ -``` - -### 一键安装脚本 - -```bash -# 使用 sudo 权限执行 -sudo bash install.sh -``` - -该脚本会: -1. 检测/安装 Java 17 -2. 创建 `/opt/serverguard/` 工作目录 -3. 等待你上传 jar 包(通过 `scp` 或其他方式) -4. 自动创建并启用 systemd 服务 -5. 启动服务并验证状态 +详见项目根目录 `CLAUDE.md`,核心原则: +- **YOLO 模式**:直接执行,不等确认,不犹豫 +- **中文注释**:每个方法和关键逻辑必须有详细中文注释,解释 WHY 而非 WHAT +- **测试纪律**:修改前后必须跑全量测试 +- **频繁提交**:每个有意义的改动单独提交 Git,中文 commit message +- **零伪代码**:每一行代码都必须可编译、可运行、可验证 --- -## 📦 部署指南 +## 性能特性 -### Systemd 服务 - -仓库提供了两个 systemd unit 文件: - -**`systemd/minecraft.service`** — Minecraft 服务端(Aluer 的前提依赖): - -```ini -[Unit] -Description=Minecraft PaperMC Server -After=network.target - -[Service] -Type=simple -User=minecraft -WorkingDirectory=/opt/minecraft -ExecStart=/usr/bin/java -Xms4G -Xmx4G -jar paper-1.21.11.jar nogui -Restart=on-failure -RestartSec=10 -StartLimitBurst=3 - -[Install] -WantedBy=multi-user.target -``` - -**`systemd/serverguard.service`** — Aluer 防护系统: - -```ini -[Unit] -Description=Aluer ServerGuard Protection System -After=network.target minecraft.service -Requires=minecraft.service - -[Service] -Type=simple -User=root -WorkingDirectory=/opt/serverguard -ExecStart=/usr/bin/java -jar serverguard.jar -Restart=always -RestartSec=5 - -[Install] -WantedBy=multi-user.target -``` - -部署步骤: - -```bash -# 1. 复制服务文件 -sudo cp systemd/minecraft.service /etc/systemd/system/ -sudo cp systemd/serverguard.service /etc/systemd/system/ - -# 2. 创建 minecraft 用户 -sudo useradd -r -m -d /opt/minecraft minecraft - -# 3. 重新加载 systemd -sudo systemctl daemon-reload - -# 4. 先启动 Minecraft,再启动 Aluer -sudo systemctl enable --now minecraft -sudo systemctl enable --now serverguard - -# 5. 查看运行状态 -sudo systemctl status minecraft serverguard - -# 6. 查看 Aluer 日志 -sudo journalctl -u serverguard -f -``` - -### sudo 权限配置 - -Aluer 需要能执行 `systemctl restart minecraft` 来重启 Minecraft 服务端。将 `systemd/sudoers.serverguard` 复制到 `/etc/sudoers.d/`: - -```bash -sudo cp systemd/sudoers.serverguard /etc/sudoers.d/serverguard -sudo chmod 440 /etc/sudoers.d/serverguard -``` - -该文件内容: - -``` -%sudo ALL=(ALL) NOPASSWD: /bin/systemctl restart minecraft -%sudo ALL=(ALL) NOPASSWD: /bin/systemctl stop minecraft -%sudo ALL=(ALL) NOPASSWD: /bin/systemctl start minecraft -%sudo ALL=(ALL) NOPASSWD: /bin/systemctl status minecraft -%sudo ALL=(minecraft) NOPASSWD: /usr/bin/rcon-cli * -``` - -### 反向代理(可选) - -如果要将 Web 控制台暴露到公网,建议在前面放置 Nginx: - -```nginx -server { - listen 443 ssl; - server_name console.your-server.com; - - # 基础鉴权 - auth_basic "Aluer Console"; - auth_basic_user_file /etc/nginx/.htpasswd; - - location / { - proxy_pass http://127.0.0.1:8080; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - } -} -``` - -> **警告**:绝对不要将 Aluer 的 8080 端口直接暴露到公网,WAF 模块仅提供基础 Web 防护,不足以替代专业反向代理的安全加固。 +| 指标 | Plugin 模式 | External 模式 | +|------|------------|---------------| +| 通信延迟 | < 1ms(同机 WebSocket) | 取决于 RCON 响应 | +| 事件吞吐 | 50,000+ 事件/秒 | 10,000+ 事件/秒 | +| 在线玩家支持 | 100+ (单 Agent) | 100+ | +| 内存占用 | ~50MB(插件部分) | ~200MB(完整引擎) | +| 模块热开关 | 支持 | 支持 | +| 自动恢复 | 全自动(自愈系统) | 全自动 | +| DDoS 防御 | 多层协同 | 多层协同 | +| AI 决策延迟 | ~45秒(DeepSeek 分析) | ~45秒 | +| 适合场景 | 生产服务器(推荐) | 监控/备份场景 | --- -## ⚙️ 配置参考 +## 许可证 -### 完整配置树 - -以下是 `application.yml` 中的所有顶级配置节点及其用途。每个节点都可以通过 YAML 文件或环境变量覆盖。 - -``` -serverguard -├── minecraft # Minecraft 服务端连接配置 -│ ├── service-name # systemd 服务名(默认: minecraft) -│ ├── process-name # 进程匹配名(用于进程存活检测) -│ ├── jar-file # PaperMC jar 文件名 -│ ├── working-dir # Minecraft 服务端工作目录 -│ ├── java-opts # JVM 启动参数 -│ ├── check-interval-seconds # 监控检查间隔(默认: 5s) -│ └── rcon -│ ├── enabled # 是否启用 RCON 连接 -│ ├── host # RCON 主机(默认: localhost) -│ ├── port # RCON 端口(默认: 25575) -│ └── password # RCON 密码(${RCON_PASSWORD}) -│ -├── monitor # 监控阈值配置 -│ ├── tps-threshold # TPS 告警阈值(默认: 15) -│ ├── cpu-threshold # CPU 使用率告警阈值 %(默认: 80) -│ ├── memory-threshold # 内存使用率告警阈值 %(默认: 85) -│ ├── connection-threshold # 连接数异常阈值 -│ ├── log-watch-lines # 日志尾部跟踪行数 -│ └── log-path # Minecraft 日志文件路径 -│ -├── alert # 告警通知配置 -│ ├── enabled # 是否启用告警 -│ └── email -│ ├── smtp-host # SMTP 服务器 -│ ├── smtp-port # SMTP 端口(默认: 587) -│ ├── username # 发件邮箱(${ALUER_ALERT_SMTP_USERNAME}) -│ ├── password # SMTP 授权码(${ALUER_ALERT_SMTP_PASSWORD}) -│ ├── to # 收件人列表(环境变量注入) -│ └── rate-limit -│ ├── per-type-seconds # 同类型告警冷却时间(默认: 300s) -│ └── max-emails-per-minute # 每分钟最大邮件数 -│ -├── ai # AI 引擎配置 -│ ├── enabled # 是否启用 AI 分析 -│ ├── use-isolation-forest # 是否使用孤立森林异常检测 -│ ├── use-prediction # 是否使用时序预测 -│ ├── sliding-window-size # 滑动窗口大小(指标数据点数) -│ ├── anomaly-threshold # 异常检测阈值(0-1) -│ ├── prediction-horizon-minutes # 预测时间范围(分钟) -│ └── deepseek -│ ├── enabled # 是否启用 DeepSeek -│ ├── api-key # API Key(${DEEPSEEK_API_KEY}) -│ ├── base-url # API 地址(默认: https://api.deepseek.com) -│ ├── model # 模型名(默认: deepseek-chat) -│ ├── max-tokens # 最大输出 token 数 -│ ├── temperature # 生成温度(0-1,建议 0.35) -│ ├── auto-analyze-alerts # 是否自动分析告警 -│ ├── analysis-interval-seconds # AI 分析间隔 -│ └── auto-execute -│ ├── enabled # 是否启用 AI 自动执行防御操作 -│ ├── ban-ip # 允许自动封禁 IP -│ ├── kill-entity # 允许自动清除实体 -│ ├── clear-lag # 允许自动清理延迟 -│ ├── set-spawn-rate # 允许自动调节生物生成率 -│ ├── kick-player # 允许自动踢出玩家 -│ ├── whitelist # 允许自动开启白名单 -│ └── min-confidence # 自动执行的最低置信度(默认: 88) -│ -├── security # 安全模块总配置(见下面子节点) -│ ├── enabled # 主开关 -│ ├── auto-ban-vpn # 自动封禁 VPN/代理用户 -│ ├── check-on-login # 玩家登录时执行安全检查 -│ ├── max-connections-per-ip # 单 IP 最大连接数 -│ ├── block-common-exploits # 拦截常见漏洞利用 -│ ├── log-all-commands # 记录所有命令 -│ │ -│ ├── minecraft-defense # Minecraft 协议层防御 -│ │ ├── game-tcp-port=25565 -│ │ ├── query-udp-port=25565 -│ │ ├── rcon-tcp-port=25575 -│ │ ├── status-ping-threshold=25 -│ │ ├── login-burst-threshold=12 -│ │ ├── bot-swarm-threshold=15 -│ │ ├── query-flood-threshold=30 -│ │ ├── rcon-brute-force-threshold=5 -│ │ └── compression-payload-threshold=8192 -│ │ -│ ├── ddos-defense # DDoS 多层检测阈值 -│ │ ├── syn-flood-threshold=100 -│ │ ├── udp-flood-threshold=200 -│ │ ├── icmp-flood-threshold=100 -│ │ ├── http-flood-threshold=150 -│ │ ├── slow-connection-threshold=150 -│ │ ├── amplification-threshold=20 -│ │ └── minecraft-* # Minecraft 专属 DDoS 阈值 -│ │ -│ ├── anti-intrusion # 入侵检测配置 -│ │ ├── monitor-commands # 监控可疑命令 -│ │ ├── monitor-processes # 监控进程变更 -│ │ ├── monitor-files # 监控文件变更 -│ │ ├── monitor-plugins # 监控插件目录 -│ │ ├── monitor-systemd # 监控服务状态 -│ │ ├── monitor-rcon # 监控 RCON 爆破 -│ │ └── file-integrity # 文件完整性监控 -│ │ ├── enabled -│ │ ├── max-depth=5 # 扫描深度 -│ │ └── monitored-paths # 监控路径列表 -│ │ -│ ├── host-enforcement # 本机防火墙强制 -│ │ ├── enabled -│ │ ├── dry-run=true # 首次部署建议开启 -│ │ ├── preferred-backend=auto # iptables / ufw / nftables -│ │ ├── default-block-minutes=60 -│ │ ├── default-rate-limit-per-minute=120 -│ │ └── mirror-to-cloud-edge=true # 同步到 Cloudflare -│ │ -│ ├── cloud-edge # Cloudflare 边缘防护 -│ │ ├── enabled -│ │ ├── dry-run=true -│ │ ├── provider=cloudflare -│ │ ├── zone-id / api-key / api-email -│ │ ├── default-block-mode=block -│ │ ├── default-challenge-mode=challenge -│ │ └── enable-under-attack-on-critical=true -│ │ -│ ├── orchestration # 编排策略 -│ │ ├── enabled -│ │ ├── allow-local-block=true -│ │ ├── allow-edge-challenge=true -│ │ ├── allow-minecraft-defense=true -│ │ └── notify-on-critical=true -│ │ -│ ├── autonomy # 自主防御策略 -│ │ ├── enabled -│ │ ├── deepseek-dominant=true # L1 是否优先于 L2 -│ │ ├── quiet-console=true # 减少终端输出 -│ │ ├── loop-interval-seconds=45 -│ │ ├── min-risk-score-for-action=70 -│ │ ├── critical-risk-score=90 -│ │ ├── workflow-cooldown-seconds=180 -│ │ ├── max-actions-per-hour=12 -│ │ └── require-second-signal-for-containment=true -│ │ -│ ├── shield # Mirage Shield 配置 -│ │ ├── enabled -│ │ ├── auto-mode=true -│ │ ├── auto-enable-under-attack=true -│ │ ├── heat-trigger=78 -│ │ ├── resonance-trigger=72 -│ │ ├── threat-score-trigger=85 -│ │ ├── edge-challenge-offender-limit=6 -│ │ ├── shelter-rate-limit-per-minute=45 -│ │ ├── attacker-notice-enabled=true -│ │ └── deterrence-message="..." -│ │ -│ ├── kernel # Kernel 引擎配置 -│ │ ├── enabled -│ │ ├── pulse-interval-seconds=30 -│ │ ├── pulse-history-size=180 -│ │ ├── journal-size=300 -│ │ ├── echo-retention-minutes=180 -│ │ ├── adaptive-weights=true -│ │ ├── directive-heat-threshold=60 -│ │ └── lockdown-heat-threshold=82 -│ │ -│ ├── task-bus # 任务总线配置 -│ │ ├── enabled -│ │ ├── auto-dispatch=true -│ │ ├── dispatch-interval-seconds=10 -│ │ ├── queue-limit=200 -│ │ └── history-limit=300 -│ │ -│ └── self-healing # 自愈编排配置 -│ ├── enabled -│ ├── dry-run=true # 首次部署建议开启 -│ ├── loop-interval-seconds=45 -│ ├── auto-backup-before-recovery=true -│ ├── auto-whitelist-on-swarm=true -│ ├── allow-soft-restart=true -│ ├── tps-emergency-threshold=12 -│ ├── cpu-emergency-threshold=92.0 -│ ├── memory-emergency-threshold=95.0 -│ └── max-recovery-actions-per-hour=8 -│ -├── dashboard # Web 控制台配置 -│ ├── enabled -│ ├── title="Aluer Nebula Console" -│ ├── subtitle="PaperMC defense, recovery, and remote operations fabric" -│ ├── refresh-interval-seconds=6 -│ ├── compact-terminal=true -│ └── ssh-gateway -│ ├── enabled -│ ├── session-timeout-minutes=30 -│ ├── max-sessions=6 -│ ├── command-timeout-seconds=25 -│ ├── strict-host-key-checking=false -│ ├── allow-private-key-paste=true -│ ├── require-engine-handshake=true -│ └── handshake-ttl-seconds=30 -│ -├── backup # 备份配置 -│ ├── enabled -│ ├── backup-dir=/opt/minecraft/backups -│ ├── world-dir=/opt/minecraft/world -│ ├── plugin-dir=/opt/minecraft/plugins -│ ├── interval-hours=24 -│ ├── max-backups=7 -│ ├── compress=true -│ ├── backup-plugins=true -│ └── notify-on-complete=true -│ -├── schedule # 计划任务 -│ ├── enabled -│ ├── daily-restart / restart-time="04:00" -│ ├── save-before-restart / announce-restart -│ ├── weekly-backup / backup-day="sunday" -│ └── clear-lag-daily / clear-lag-time="02:00" -│ -├── chat-filter # 聊天过滤 -│ ├── enabled -│ ├── block-ip / block-profanity / block-advertising -│ ├── block-spam / block-illegal -│ ├── spam-threshold=5 -│ ├── spam-window-seconds=10 -│ ├── mute-on-violation / mute-duration-minutes=5 -│ ├── kick-on-repeat / max-violations-before-kick=3 -│ └── custom-words[] -│ -├── announcement # 定时公告 -│ ├── interval-seconds=300 -│ └── messages[] -│ -└── afk # AFK 管理 - ├── enabled - ├── afk-timeout-minutes=5 - ├── max-afk-minutes=30 - ├── teleport-to-afk-zone - ├── afk-zone="0,100,0" - └── auto-logout -``` - -### 环境变量注入表 - -配置文件中所有 `${VAR_NAME:default}` 形式的值都可以通过环境变量覆盖: - -| 环境变量 | 对应配置路径 | 默认值 | -|----------|-------------|--------| -| `RCON_PASSWORD` | `serverguard.minecraft.rcon.password` | (空) | -| `DEEPSEEK_API_KEY` | `serverguard.ai.deepseek.api-key` | (空) | -| `DEEPSEEK_BASE_URL` | `serverguard.ai.deepseek.base-url` | `https://api.deepseek.com` | -| `DEEPSEEK_MODEL` | `serverguard.ai.deepseek.model` | `deepseek-chat` | -| `ALUER_ALERT_SMTP_USERNAME` | `serverguard.alert.email.username` | (空) | -| `ALUER_ALERT_SMTP_PASSWORD` | `serverguard.alert.email.password` | (空) | -| `ALUER_ALERT_EMAIL_PRIMARY` | `serverguard.alert.email.to[0]` | (空) | -| `ALUER_ALERT_EMAIL_SECONDARY` | `serverguard.alert.email.to[1]` | (空) | -| `ALUER_CLOUDFLARE_ZONE_ID` | `serverguard.security.cloud-edge.zone-id` | (空) | -| `ALUER_CLOUDFLARE_API_KEY` | `serverguard.security.cloud-edge.api-key` | (空) | -| `ALUER_CLOUDFLARE_EMAIL` | `serverguard.security.cloud-edge.api-email` | (空) | - ---- - -## 📋 模块清单 - -### AI 决策层 (`com.aluer.ai`) - -| 类 | 文件 | 功能 | -|----|------|------| -| `AluerSovereignEngine` | `ai/AluerSovereignEngine.java` | **L1 主控引擎**。每 45 秒收集全网态势 JSON → DeepSeek 生成 `AutonomyDirective`(workflow + defenseLevel + riskScore)。内置工作流名称校验白名单,防止 LLM 幻觉产生无效指令。 | -| `DeepSeekClient` | `ai/DeepSeekClient.java` | **DeepSeek API 客户端**。原生 `HttpURLConnection` 实现。支持 3 种调用模式:告警分析(`analyzeAlert`)、健康报告(`getServerHealthReport`)、自由问答(`askQuestion`)和自治指令规划(`planAutonomousDefense`)。内置从 Markdown/文本中提取 JSON 的容错解析。 | -| `AIAutonomousService` | `ai/AIAutonomousService.java` | **L3 执行落地层**。读取 L1 Sovereign 指令 + L2 Kernel 指令,执行冲突仲裁、操作冷却检查、每小时操作次数限制、双信号确认,最终将决策转化为 RCON 命令。 | -| `AIStrategyEngine` | `ai/AIStrategyEngine.java` | **策略匹配引擎**。根据威胁类型和严重程度映射最佳防御策略(暴力破解 → 临时封禁+验证码,DDoS → 流量清洗+限流)。 | -| `AnomalyDetector` | `ai/AnomalyDetector.java` | **孤立森林异常检测**。基于 Apache Commons Math3 实现,对 CPU/内存/TPS/连接数等多维指标进行无监督异常检测。 | -| `TimeSeriesPredictor` | `ai/TimeSeriesPredictor.java` | **时序预测器**。基于滑动窗口的历史指标数据,预测未来 60 分钟内的 TPS 走势,提前预警性能瓶颈。 | -| `AdaptiveThreshold` | `ai/AdaptiveThreshold.java` | **自适应阈值**。学习服务器历史负载模式,动态调整各项监控告警的触发阈值,降低凌晨低负载时段的误报率。 | - -### Kernel 内核层 (`com.aluer.kernel`) - -| 类 | 文件 | 功能 | -|----|------|------| -| `AluerKernelEngine` | `kernel/AluerKernelEngine.java` | **L2 内核引擎**。每 30 秒执行一次 Pulse 循环。内部运行 5 个虚拟模块(ThreatMesh / CommandLattice / HardeningMatrix / PerimeterWard / EchoGrid),加权汇聚信号,计算 heat/resonance/control 三维压力,产出 `KernelDirective`。支持自适应权重调整和 EchoGrid 攻击者记忆衰减。 | -| `AluerKernelTaskBus` | `kernel/AluerKernelTaskBus.java` | **任务总线**。插件化的任务执行框架。4 个内置 Plugin(Insight / Stability / Defense / Recovery)按优先级派发任务。支持任务队列限长、执行历史追踪。 | -| `AluerSelfHealingOrchestrator` | `kernel/AluerSelfHealingOrchestrator.java` | **自愈编排器**。每 45 秒运行一次恢复检查。检测 TPS/CPU/内存是否触发紧急阈值。恢复动作包括:软重启、清实体、调节生物生成率、开启白名单(bot swarm 场景)、恢复前自动备份。每小时最多 8 次恢复操作。 | - -### 安全防护层 (`com.aluer.security`) - -这是系统中规模最大的包,包含 85+ 个安全服务(含 31 个高级扩展安全模块,V4.0 完整版): - -| 类别 | 类 | 功能 | -|------|-----|------| -| **DDoS 防御** | `DDoSProtectionService` | SYN/HTTP/UDP/ICMP Flood 检测,Minecraft 专属 Status/Login/Rcon/Query Flood 识别 | -| | `DDoSDefenseCoordinator` | 统一协调多个 DDoS 检测源,防重复封禁 | -| | `DistributedAttackMitigationService` | 分布式攻击缓解,跨节点协同 | -| | `MinecraftProtocolSecurityService` | Minecraft 协议层深度防御(Status Ping / Login Burst / Bot Swarm / Compression Bomb) | -| **防火墙** | `FirewallService` | iptables/ufw 规则管理,黑白名单维护 | -| | `HostEnforcementService` | 本机防火墙强制,支持 auto/iptables/ufw/nftables 后端 | -| | `NetworkMonitorService` | 进出站流量统计与异常检测 | -| | `NetworkSegmentationService` | 网络分段隔离 | -| **入侵检测** | `IntrusionDetectionService` | 基于签名的入侵检测 | -| | `IntrusionPreventionSystem` | 自动阻断入侵行为 | -| | `HostIntrusionCountermeasureService` | 主机层面入侵反制 | -| | `LogAnalysisService` | 日志异常模式匹配 | -| | `LogCorrelationService` | 多源日志关联分析 | -| **应用安全** | `WebApplicationFirewall` (WAF) | SQLi / XSS / 路径遍历 / Header 注入防护,客户端信誉评分 | -| | `WafRequestFilter` | WAF 的 HTTP 请求过滤拦截器 | -| | `APIRateLimitService` | API 接口速率限制 | -| | `RateLimitService` | 通用速率限制引擎 | -| **高级防御** | `HoneypotService` | 蜜罐诱饵端口,捕获扫描者,收集攻击指纹 | -| | `ZeroTrustArchitectureService` | 持续身份验证,最小权限校验 | -| | `AdvancedMalwareDetectionService` | 恶意文件扫描(插件后门、可疑 jar) | -| | `EndpointDetectionResponseService` | EDR 端点检测与响应 | -| | `ContainerSecurityService` | 容器安全检查 | -| **网络分析** | `TrafficAnalysisService` | 流量模式分析 | -| | `PacketInspectionService` | 深度包检测(DPI) | -| | `FlowAnalyzerService` | NetFlow/sFlow 流分析 | -| | `PortScanDetectionService` | 端口扫描检测与扫描者封禁 | -| | `ProtocolAnalysisService` | 协议异常检测 | -| **IP 情报** | `IPReputationService` | IP 信誉评分,全局黑名单查询 | -| | `GeoIPService` | IP 地理位置查询,按国家/地区过滤 | -| | `ThreatIntelligenceService` | 威胁情报源集成(可配置多个 Feed) | -| | `VPNDetectionService` | VPN/代理/托管服务商 IP 检测 | -| **SSL/TLS** | `SSLMonitorService` | SSL/TLS 证书过期监控 | -| | `SSLTLSCertificateService` | 证书管理 | -| **安全运维** | `SIEMService` | 安全信息与事件管理,关联碎片化事件识别攻击链 | -| | `SecurityOrchestrationService` | 安全编排,协调 L1/L2 决策与具体防御模块 | -| | `SecurityAutomationScheduler` | 自动化安全任务调度 | -| | `SecurityBaselineHardeningService` | 安全基线审计与加固(系统配置、文件权限、服务状态) | -| | `BackupSecurityService` | 备份文件安全保护 | -| **命令安全** | `CommandExecutionGuardService` | 危险命令拦截(rm -rf / wget | sh / 权限提升等) | -| **执行层** | `HostEnforcementService` | 本机防火墙强制 | -| | `CloudflareIntegrationService` | Cloudflare API 集成(IP 封禁/挑战/Under Attack 模式) | -| | `DNSSecurityService` | DNS 安全防护 | -| | `SessionManagementService` | 会话管理与异常检测 | -| | `LoadBalancerService` | 简易负载均衡 | -| | `TrafficShapingService` | 流量整形/QoS | -| | `EncryptionService` | 数据加密工具 | -| **高级扩展模块** | `JwtAuthService` | JWT Token HMAC-SHA256 认证,常量时间签名比对 | -| | `BruteForceProtectionService` | 三层时间窗口(60s/600s/3600s)暴力破解防护,渐进延迟 | -| | `AntiBotDetectionService` | Minecraft 机器人检测:命名模式/加入速度/多账号/客户端品牌 | -| | `AntiGriefDetectionService` | 方块破坏/放置速率监控,危险方块识别,容器掠夺检测 | -| | `ReverseShellDetectionService` | 50+ 反向Shell命令模式匹配,混淆命令检测 | -| | `ARPSpoofDetectionService` | ARP表基线对比,MAC变更/网关欺骗/重复MAC检测 | -| | `DNSTunnelDetectionService` | 子域名熵值分析,Base64编码识别,频率/TLD评分 | -| | `ExploitSignatureService` | 15+ 漏洞签名(Log4Shell/SQLi/XSS/反序列化/Book Exploit) | -| | `SSRFProtectionService` | 内网IP/云元数据/危险Scheme/DNS Rebinding防护 | -| | `XXEProtectionService` | XML实体注入 + Billion Laughs 攻击检测与净化 | -| | `CSPEnforcementService` | Content-Security-Policy + 8项安全响应头自动生成 | -| | `DatabaseFirewallService` | SQL注入检测(UNION/注释/堆叠查询/时间盲注) | -| | `DataLossPreventionService` | 12种敏感数据模式(邮箱/API Key/SSH Key/JWT/银行卡) | -| | `MemoryProtectionService` | JVM堆监控/GC过载/内存泄漏模式识别 | -| | `ProcessInjectionDetectionService` | 进程线程尖峰/内存映射/非标准native库检测 | -| | `SecureFileDeletionService` | DoD多pass覆写(0x00/随机/0xFF/0xAA)安全删除 | -| | `ForensicsCollectorService` | 6种取证数据(进程/网络/文件/日志)案件管理 | -| | `IncidentResponseService` | 5套响应剧本(DDoS/爆破/入侵/MC漏洞/数据泄露) | -| | `ThreatHuntingService` | 10种主动狩猎规则(持久化/横向移动/提权/挖矿/WebShell) | -| | `ComplianceScannerService` | 7大类20+项合规检查,自动评分(0-100%) | -| **Minecraft专属** | `AntiXrayDetectionService` | X-ray透视检测:钻石/石头比率分析、直线挖掘、黑暗环境精准采矿 | -| | `AntiFlyDetectionService` | 飞行/速度/传送外挂检测:垂直限速、水平限速、留空时间、无摔伤检测 | -| | `AntiDupeDetectionService` | 物品复制检测:堆叠溢出、高价值物品暴涨、9种已知复制方法监测 | -| | `CrashExploitProtectionService` | 崩溃漏洞防护:超大包/负长度/NBT嵌套/书与笔/Sign炸弹/Tile Entity洪水 | -| | `LagMachineDetectionService` | 卡服机检测:Observer链/TNT堆叠/红石密度/实体刷怪/掉落方块洪流 | -| **V4.0 扩展** | `GeoBlockService` | 地理IP封锁:国家/地区黑白名单,高风险Minecraft攻击来源国拦截 | -| | `PlayerSessionValidationService` | 玩家会话验证:UUID格式/离线模式/正版检测/会话重放/多账号识别 | -| | `PluginVerificationService` | 插件完整性校验:SHA-256哈希对比、恶意插件名检测、JAR结构检查 | -| | `ConnectionThrottleService` | 连接速率限制:多时间窗口IP追踪、递增延迟(2s/5s/15s/30s)、并发上限 | -| | `BackupIntegrityService` | 备份完整性验证:SHA-256校验和、文件存在性/大小对比、6小时自动扫描 | -| | `AntiSkinSpoofService` | 皮肤伪造检测:知名主播皮肤冒充、可疑URL、皮肤变更频率、模型类型异常 | - -### 运营控制层 (`com.aluer.console`) - -| 类 | 功能 | -|----|------| -| `AluerOperationsCenterService` | **运营总控台**,聚合全部子系统状态,输出给 Web 控制台的 `/api/console/overview` 接口 | -| `AluerMirageShieldService` | **幻影护盾**,四级模式(OBSERVE → FORTIFY → MIRAGE → SHELTER),攻击者威慑通知,自动模式切换 | -| `RemoteSshGatewayService` | **远程 SSH 网关**,内置终端,支持 Sovereign Handshake 连接审批 + 命令守卫联动 | -| `ConsoleStreamController` | **SSE 实时流**,通过 Server-Sent Events 推送实时总览数据到 Web 前端 | - -### 监控采集层 (`com.aluer.monitor`) - -| 类 | 功能 | -|----|------| -| `ProcessMonitor` | 进程存活检测,崩溃自动重启 Minecraft 服务端 | -| `ResourceMonitor` | 系统资源采集(CPU/内存/磁盘 I/O),通过 `/proc` 和 JMX 获取 | -| `ConnectionMonitor` | 网络连接统计,检测 Connection Flood 攻击模式 | -| `LogMonitor` | Minecraft `latest.log` 实时追踪,捕获崩溃堆栈和异常登录模式 | - -### 核心服务层 (`com.aluer.service`) - -| 类 | 功能 | -|----|------| -| `ServerGuardService` | **系统总控**,`CommandLineRunner` 入口,调度全部监控循环和 AI 分析循环 | -| `RconClient` | Minecraft RCON 协议客户端,所有游戏内命令的通道 | -| `AutoExecutor` | AI 决策到 RCON 命令的翻译器,将抽象的防御动作("封禁IP")转为具体指令(`/ban-ip 1.2.3.4`) | - -### Web 交互层 (`com.aluer.web`) - -| 类 | 功能 | -|----|------| -| `DashboardController` | REST API(`/api/*`),提供状态查询、命令执行、备份管理、健康检查、攻击报告等接口 | -| `OperationsConsoleController` | 运营控制台 API(`/api/console/*`),总览数据、Shield 控制、快捷操作 | -| `ConsoleStreamController` | SSE 流推送(`/api/console/stream/overview`) | -| `HealthService` | 组件级健康检查(RCON/AI/邮件/安全/自愈),系统资源信息汇总 | -| `RequestLoggingFilter` | HTTP 请求日志过滤器,慢请求和 500 错误自动告警 | - -### 辅助功能模块 - -| 包 | 类 | 功能 | -|----|-----|------| -| `com.aluer.alert` | `EmailAlertService` | 邮件告警,支持 QQ/Gmail/自定义 SMTP,内置发送频率限制 | -| `com.aluer.backup` | `BackupService` | 世界/插件/配置定时打包备份,支持压缩和自动清理旧备份 | -| `com.aluer.anticheat` | `AntiCheatService` | 反作弊联动,汇总反作弊插件数据,智能判罚 | -| `com.aluer.vpn` | `VPNDetectionService` | VPN/代理 IP 检测,防止作弊者绕过 IP 封禁 | -| `com.aluer.chat` | `ChatFilterService` | 游戏内聊天过滤(脏话/广告/钓鱼链接/刷屏) | -| `com.aluer.punishment` | `PunishmentService` | 统一处罚管理(封禁/踢出/禁言),记录历史 | -| `com.aluer.audit` | `SecurityAuditService` | 安全审计日志,记录所有管理员操作和安全事件 | -| `com.aluer.world` | `WorldManagementService` | Minecraft 世界管理(动态加载/卸载/列表) | -| `com.aluer.metrics` | `MetricsCollectionService` | 指标统一汇总,标准化各 Monitor 的采集数据 | -| `com.aluer.profiler` | `PerformanceProfiler` | 性能分析器,CPU/内存/Tick 耗时深度剖析 | -| `com.aluer.schedule` | `ScheduledTaskService` | 计划任务引擎(定时重启/备份/清 lag/公告) | -| `com.aluer.export` | `DataExportService` | 安全数据导出(审计日志/攻击记录/性能报告) | -| `com.aluer.command` | `AdminCommands` / `TestCommands` | Spring Shell 管理命令和测试命令 | -| `com.aluer.notification` | `WebhookService` / `AttackReportService` | Discord/Slack Webhook 告警通知;HTML 攻击报告自动生成与导出 | - -### 数据模型 (`com.aluer.model`) - -| 类 | 字段 | 说明 | -|----|------|------| -| `AlertEvent` | type, message, rootCause, timestamp, confidence, suggestedAction | 标准化告警事件 | -| `AlertType` | PROCESS_DEAD / TPS_LOW / CPU_HIGH / MEM_HIGH / CONNECTION_FLOOD / LOG_ATTACK / BACKUP_FAILED / AI_ANOMALY | 告警类型枚举 | -| `MetricsData` | tps, cpuUsage, memoryUsage, onlinePlayers, connections, tickTime | 服务器性能快照 | - ---- - -## 🛡️ 防御等级与自动响应 - -### 四级防御体系 - -系统根据 Kernel heat 和 Sovereign 综合判定自动切换防御等级: - -| 等级 | heat 范围 | 触发条件 | 自动行为 | -|------|-----------|----------|----------| -| `NORMAL` | < 45 | 正常运行 | 常规监控,异常记录到日志,不执行主动防御 | -| `ELEVATED` | 45–69 | 单个模块压力上升 | 加强检测频率,IP 信誉查询启用,高风险 IP 标记 | -| `HIGH` | 70–81 | 多模块同时报警 | 自动封禁高风险 IP,速率限制启用,边缘挑战开启 | -| `LOCKDOWN` | ≥ 82 | 严重复合攻击 | 白名单模式,Cloudflare Under Attack,拒绝新连接,邮件紧急通知 | - -### Mirage Shield 模式切换 - -Mirage Shield 是面向攻击者的偏转护盾,有 4 种运行模式: - -| 模式 | 含义 | 自动触发条件 | -|------|------|-------------| -| `OBSERVE` | 仅观察,不干预 | 默认模式 | -| `FORTIFY` | 加固防御 | heat ≥ 78 或 threat_score ≥ 85 | -| `MIRAGE` | 镜像偏转 | resonance ≥ 72 且有高置信度攻击者 | -| `SHELTER` | 避难所模式 | heat ≥ 82 且 resonance ≥ 80,进入严格限流 | - -Mirage Shield 在 `MIRAGE` 和 `SHELTER` 模式下,会向检测到的攻击 IP 返回威慑消息(`deterrence-message` 配置项)。 - -### 自愈编排触发条件 - -`AluerSelfHealingOrchestrator` 在满足以下任一条件时触发恢复流程: - -| 条件 | 阈值 | 恢复动作 | -|------|------|----------| -| TPS 低于紧急线 | < 12 TPS | `clear-lag` + `kill-entity` + `set-spawn-rate 低` | -| CPU 高于紧急线 | > 92% | 优先 `clear-lag`,若无效则考虑软重启 | -| 内存高于紧急线 | > 95% | `save-all` → 通知玩家 → 软重启 | -| Bot Swarm 检测 | ≥ 15 个并发假玩家 | `whitelist on` + 封禁来源 IP | - -所有恢复动作在 `dry-run=true` 时仅记录日志而不实际执行。 - ---- - -## 🌐 API 参考 - -### 系统状态 API - -| 方法 | 路径 | 说明 | -|------|------|------| -| `GET` | `/api/status` | 系统运行状态 | -| `GET` | `/api/server/info` | Minecraft 服务器信息 | -| `GET` | `/api/performance` | TPS / CPU / 内存指标 | -| `POST` | `/api/command/execute` | 执行 RCON 命令(参数 `command`) | - -**示例**: - -```bash -# 执行 RCON 命令 -curl -X POST http://localhost:8080/api/command/execute \ - -d "command=list" - -# 获取性能指标 -curl http://localhost:8080/api/performance -``` - -### 安全态势 API - -| 方法 | 路径 | 说明 | -|------|------|------| -| `GET` | `/api/security/stats` | 安全总览 | -| `GET` | `/api/security/network/posture` | 网络态势详情 | -| `GET` | `/api/security/network/offenders?limit=10` | 高风险 IP 列表 | -| `GET` | `/api/security/network/incidents?limit=20` | 安全事件列表 | -| `GET` | `/api/security/network/ip?ip=1.2.3.4` | 单 IP 深度检查 | -| `POST` | `/api/security/network/quarantine` | 隔离 IP(参数 `ip`, `actor`, `reason`) | -| `POST` | `/api/security/network/release` | 释放 IP(参数同上) | - -**示例**: - -```bash -# 查询 IP 信誉 -curl "http://localhost:8080/api/security/network/ip?ip=45.33.32.156" - -# 手动隔离 IP -curl -X POST "http://localhost:8080/api/security/network/quarantine" \ - -d "ip=45.33.32.156&actor=admin&reason=syn flood detected" -``` - -### 控制台操作 API - -| 方法 | 路径 | 说明 | -|------|------|------| -| `GET` | `/api/console/overview` | 完整运营总览(所有子系统状态聚合) | -| `GET` | `/api/console/stream/overview` | SSE 实时流推送 | -| `POST` | `/api/console/shield/engage` | 手动切换 Shield 模式(参数 `mode`, `reason`) | -| `POST` | `/api/console/quick-action` | 快捷操作(参数 `action`:`backup-now` / `shield-mirage` / `shield-shelter`) | - -### SSH 网关 API - -| 方法 | 路径 | 说明 | -|------|------|------| -| `POST` | `/api/console/ssh/handshake` | Sovereign 握手审批(参数 `host`, `port`, `username`, `purpose`) | -| `POST` | `/api/console/ssh/connect` | 建立 SSH 连接(参数 `alias`, `host`, `port`, `username`, `password`, `privateKeyPath`, `handshakeToken`) | -| `POST` | `/api/console/ssh/execute` | 执行远程命令(参数 `sessionId`, `command`) | -| `DELETE` | `/api/console/ssh/{sessionId}` | 断开 SSH 会话 | - -**SSH 网关的安全设计**: - -1. **Sovereign Handshake 前置**:连接前必须先通过握手审批,Kernel 根据当前 heat 和风险评分决定是否批准 -2. **命令守卫联动**:执行的每条命令都经过 `CommandExecutionGuardService` 审查,危险命令被标记和阻断 -3. **会话超时**:默认 30 分钟无活动自动断开 -4. **审计同步**:所有 SSH 操作自动记录到 `SecurityAuditService` - -### 健康检查 API - -| 方法 | 路径 | 说明 | -|------|------|------| -| `GET` | `/api/health` | 完整健康报告(组件状态 + 系统资源) | -| `GET` | `/api/health/live` | 存活探针(K8s liveness probe) | -| `GET` | `/api/health/ready` | 就绪探针(K8s readiness probe) | - -**示例响应 (`/api/health`)**: - -```json -{ - "status": "HEALTHY", - "uptimeSeconds": 86400, - "components": { - "rcon": {"status": "UP", "host": "localhost:25575"}, - "deepseek-ai": {"status": "UP", "model": "deepseek-chat"}, - "email-alert": {"status": "UP"}, - "security": {"status": "UP", "kernelEnabled": true}, - "self-healing": {"status": "UP", "dryRun": true} - }, - "system": { - "memory": {"usedMB": 320, "maxMB": 4096, "usagePercent": 7.8}, - "heapUsedMB": 180, - "systemCpuLoad": 12.5 - } -} -``` - -### 通知与报告 API - -| 方法 | 路径 | 说明 | -|------|------|------| -| `GET` | `/api/attacks/recent?limit=20` | 最近攻击记录 | -| `POST` | `/api/attacks/report` | 生成 HTML 攻击报告 | -| `POST` | `/api/webhook/test` | 测试 Discord/Slack Webhook | - -**Webhook 配置**(`application.yml`): - -```yaml -serverguard: - webhook: - enabled: false - discord-url: ${ALUER_WEBHOOK_DISCORD:} - slack-url: ${ALUER_WEBHOOK_SLACK:} -``` - -### 备份管理 API - -| 方法 | 路径 | 说明 | -|------|------|------| -| `GET` | `/api/backup/list` | 备份列表 | -| `POST` | `/api/backup/create` | 创建新备份(参数 `name`) | - ---- - -## 🖥️ Web 控制台 - -Aluer 内置 React 19 + Vite 6 构建的单页应用控制台(Nebula Console)。 - -### 页面布局 - -``` -┌────────────┬───────────────────────────────────────────────┐ -│ Command │ Hero Panel(Mirage Shield 当前模式) │ -│ Rail │ ┌─────────────┐ ┌──────────────┐ │ -│ ──────── │ │ Risk Score │ │ Shield 操作 │ │ -│ System │ │ Kernel Heat │ │ FORTIFY │ │ -│ Title │ │ Resonance │ │ MIRAGE │ │ -│ ──────── │ └─────────────┘ │ SHELTER │ │ -│ Stream │ │ RECOVERY │ │ -│ Status │ └──────────────┘ │ -│ ──────── ├───────────────────────────────────────────────┤ -│ Quick │ Module Constellation(互联能力矩阵) │ -│ Actions │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ ──────── │ │ Mirage │ │ Kernel │ │ Task Bus │ │ -│ Metric │ │ Shield │ │ Engine │ │ │ │ -│ Cards │ └──────────┘ └──────────┘ └──────────┘ │ -│ TPS/CPU │ ... │ -│ Memory/ ├───────────────────────────────────────────────┤ -│ Threat │ Node Fabric(本地核心 + 远程 SSH 节点) │ -│ ├───────────────────────────────────────────────┤ -│ │ Remote SSH Workbench + Terminal │ -│ │ ┌─────────────────────────────────────────┐ │ -│ │ │ [终端输出区域,最多 120 行] │ │ -│ │ └─────────────────────────────────────────┘ │ -│ ├───────────────────────────────────────────────┤ -│ │ Threat Trace(高风险来源列表) │ -│ ├───────────────────────────────────────────────┤ -│ │ Audit Stream(审计事件流,支持筛选) │ -└────────────┴───────────────────────────────────────────────┘ -``` - -### 实时数据流 - -前端通过 **SSE(Server-Sent Events)** 接收实时数据推送: - -``` -浏览器 ──EventSource──→ /api/console/stream/overview - │ - 每 6 秒推送一次全量总览 JSON - (由 AluerOperationsCenterService 聚合) - │ - 降级机制:SSE 连接失败时自动切换为 - setInterval 轮询 /api/console/overview -``` - -### 功能清单 - -| 功能 | 说明 | -|------|------| -| Shield 控制 | 一键切换 FORTIFY / MIRAGE / SHELTER / RECOVERY 模式 | -| 性能走势 | TPS / CPU / Memory / 在线玩家 SparkBar 实时可视化 | -| 自动刷新 | 可切换开关 + 可选间隔(3s / 6s / 10s / 30s) | -| 健康检查面板 | 可折叠,显示 RCON/AI/邮件/安全/自愈 组件 UP/DOWN 状态 | -| SSH 远程终端 | 连接远程节点,执行命令,带命令守卫审查 | -| 模块监控 | 9 个模块的状态、信号值实时显示 | -| 威胁视图 | 高风险 IP 列表,score + riskLevel + 详情(最多 10 条) | -| 审计筛选 | 实时筛选审计事件、网络事件、Shield 状态变迁(最多 24 条) | - ---- - -## 🖧 Shell 命令参考 - -Aluer 启动后提供 Spring Shell 交互终端,支持自然语言和结构化命令。 - -### AI 对话 - -```bash -aluer> ai 测试一下服务器 # 执行完整服务器测试 -aluer> ai 开启防御 # 开启 AI 自主防御 -aluer> ai 查看安全状态 # 获取安全态势概览 -aluer> ai 帮我分析一下当前的卡顿原因 # DeepSeek 深度分析 -aluer> ai 查看世界 # 列出所有世界 -aluer> ask 如何提高服务器安全性 # 自由问答 -``` - -### 基础命令 - -| 命令 | 示例 | 说明 | -|------|------|------| -| `help` | `help` | 显示所有可用命令 | -| `status` | `status` | 服务器运行状态(进程/CPU/内存/连接数) | -| `test` | `test` / `test cpu` / `test memory` / `test network` / `test security` | 运行测试 | -| `metrics` | `metrics` / `metrics counters` / `metrics gauges` | 性能指标查询 | - -### 安全管理 - -| 命令 | 示例 | 说明 | -|------|------|------| -| `security` | `security` / `security ddos` / `security firewall` / `security intrusion` / `security threats` / `security vpn` / `security chat` | 各安全模块状态 | -| `defense` | `defense` / `defense on` / `defense off` / `defense list` / `defense level high` | AI 防御管控 | -| `network` | `network` / `network geoip 1.2.3.4` / `network reputation 1.2.3.4` / `network ports` | 网络分析 | - -### 玩家管理 - -| 命令 | 示例 | 说明 | -|------|------|------| -| `kick` | `kick PlayerName` | 踢出玩家 | -| `ban` | `ban PlayerName` / `ban PlayerName 作弊` | 封禁玩家 | -| `unban` | `unban PlayerName` | 解封玩家 | - -### 运维管理 - -| 命令 | 示例 | 说明 | -|------|------|------| -| `backup` | `backup` / `backup create` / `backup status` / `backup start` | 备份管理 | -| `world` | `world` / `world load world_nether` / `world unload world_nether` | 世界管理 | -| `alert` | `alert` / `alert test` / `alert send 服务器异常` | 邮件告警 | -| `audit` | `audit` / `audit recent 20` / `audit summary` | 安全审计 | -| `tasks` | `tasks` / `tasks start` | 计划任务管理 | - ---- - -## 🔧 开发指南 - -### 项目结构 - -``` -AluerIII/ -├── src/main/java/com/aluer/ -│ ├── ai/ # AI 决策引擎(7 个类) -│ │ ├── AdaptiveThreshold.java -│ │ ├── AIAutonomousService.java -│ │ ├── AIStrategyEngine.java -│ │ ├── AluerSovereignEngine.java -│ │ ├── AnomalyDetector.java -│ │ ├── AttackDetector.java -│ │ ├── DeepSeekClient.java -│ │ └── TimeSeriesPredictor.java -│ ├── kernel/ # 内核引擎(3 个类) -│ │ ├── AluerKernelEngine.java -│ │ ├── AluerKernelTaskBus.java -│ │ └── AluerSelfHealingOrchestrator.java -│ ├── security/ # 安全模块(33 个类) -│ │ ├── DDoSProtectionService.java -│ │ ├── DDoSDefenseCoordinator.java -│ │ ├── FirewallService.java -│ │ ├── WebApplicationFirewall.java -│ │ ├── IntrusionDetectionService.java -│ │ ├── IntrusionPreventionSystem.java -│ │ ├── HoneypotService.java -│ │ ├── ZeroTrustArchitectureService.java -│ │ ├── CloudflareIntegrationService.java -│ │ ├── ...(见模块清单) -│ │ └── NetworkThreatFusionService.java -│ ├── console/ # 运营控制(4 个类) -│ │ ├── AluerOperationsCenterService.java -│ │ ├── AluerMirageShieldService.java -│ │ ├── RemoteSshGatewayService.java -│ │ └── ConsoleStreamController.java -│ ├── monitor/ # 监控采集(4 个类) -│ │ ├── ProcessMonitor.java -│ │ ├── ResourceMonitor.java -│ │ ├── ConnectionMonitor.java -│ │ └── LogMonitor.java -│ ├── service/ # 核心服务(4 个类) -│ │ ├── ServerGuardService.java -│ │ ├── RconClient.java -│ │ ├── AutoExecutor.java -│ │ └── TestService.java -│ ├── web/ # Web 层(3 个类) -│ │ ├── DashboardController.java -│ │ ├── OperationsConsoleController.java -│ │ └── ConsoleStreamController.java -│ ├── config/ # 配置 -│ │ └── ServerGuardConfig.java -│ ├── model/ # 数据模型 -│ │ ├── AlertEvent.java -│ │ ├── AlertType.java -│ │ └── MetricsData.java -│ ├── terminal/ # Shell 终端 -│ │ └── AITerminal.java -│ ├── command/ # Shell 命令 -│ │ ├── AdminCommands.java -│ │ └── TestCommands.java -│ ├── alert/ # 告警 -│ │ └── EmailAlertService.java -│ ├── backup/ # 备份 -│ │ └── BackupService.java -│ ├── anticheat/ # 反作弊 -│ │ └── AntiCheatService.java -│ ├── vpn/ # VPN 检测 -│ │ └── VPNDetectionService.java -│ ├── chat/ # 聊天过滤 -│ │ └── ChatFilterService.java -│ ├── punishment/ # 处罚管理 -│ │ └── PunishmentService.java -│ ├── audit/ # 安全审计 -│ │ └── SecurityAuditService.java -│ ├── world/ # 世界管理 -│ │ └── WorldManagementService.java -│ ├── metrics/ # 指标汇聚 -│ │ └── MetricsCollectionService.java -│ ├── profiler/ # 性能分析 -│ │ └── PerformanceProfiler.java -│ ├── schedule/ # 计划任务 -│ │ └── ScheduledTaskService.java -│ ├── export/ # 数据导出 -│ │ └── DataExportService.java -│ └── ServerGuardApplication.java # Spring Boot 入口 -│ -├── src/main/resources/ -│ ├── application.yml # 主配置文件 -│ ├── logback.xml # 日志配置 -│ └── static/ # 前端构建产物 -│ ├── index.html -│ └── nebula-assets/ -│ -├── src/test/java/com/aluer/ # 测试(9 个文件) -│ ├── kernel/ -│ │ ├── AluerKernelEngineTest.java -│ │ ├── AluerKernelTaskBusTest.java -│ │ └── AluerSelfHealingOrchestratorTest.java -│ ├── security/ -│ │ ├── NetworkThreatFusionServiceTest.java -│ │ ├── SecurityBaselineHardeningServiceTest.java -│ │ └── WebApplicationFirewallTest.java -│ └── console/ -│ ├── AluerMirageShieldServiceTest.java -│ ├── AluerEngineHandshakeServiceTest.java -│ └── RemoteSshGatewayServiceTest.java -│ -├── frontend/ # React 前端 -│ ├── package.json -│ ├── vite.config.js -│ └── src/ -│ ├── main.jsx # 入口 + ErrorBoundary -│ ├── App.jsx # 主应用(Nebula Console) -│ └── styles.css # 样式 -│ -├── systemd/ # Systemd 服务文件 -│ ├── minecraft.service -│ ├── serverguard.service -│ └── sudoers.serverguard -│ -├── docs/ # 文档 -│ ├── PROJECT_SUMMARY.md -│ └── USER_MANUAL.md -│ -├── apache-maven-3.9.6/ # 内置 Maven -├── pom.xml -├── install.sh # 一键安装脚本 -├── start.sh # 启动脚本 -└── README.md -``` - -### 构建与运行 - -```bash -# 完整构建(含前端编译) -./apache-maven-3.9.6/bin/mvn clean package -DskipTests - -# 仅编译后端(跳过前端) -./apache-maven-3.9.6/bin/mvn compile - -# 运行 jar -java -jar target/serverguard.jar - -# 带自定义配置运行 -java -jar target/serverguard.jar --spring.config.location=/path/to/application.yml -``` - -### 前端开发 - -```bash -cd frontend - -# 安装依赖 -npm install - -# 启动开发服务器(http://localhost:4173) -npm run dev - -# dev server 自动将 /api 请求代理到 localhost:8080 -# 需要后端已在本地运行 - -# 构建生产版本(输出到 ../src/main/resources/static/) -npm run build -``` - -Vite 配置要点: - -```javascript -// frontend/vite.config.js -export default defineConfig({ - plugins: [react()], - server: { - host: "0.0.0.0", - port: 4173, - proxy: { "/api": "http://localhost:8080" } // 开发时代理到后端 - }, - build: { - outDir: "../src/main/resources/static", // 构建产物直接嵌入后端 - emptyOutDir: false, - assetsDir: "nebula-assets" - } -}); -``` - -### 运行测试 - -```bash -# 运行全部测试 -./apache-maven-3.9.6/bin/mvn test - -# 运行指定测试类 -./apache-maven-3.9.6/bin/mvn test -Dtest=AluerKernelEngineTest - -# 运行指定测试方法 -./apache-maven-3.9.6/bin/mvn test -Dtest=AluerKernelEngineTest#kernelPulseGeneratesCommandAbuseDirectiveAndEchoMemory - -# 查看测试报告 -cat target/surefire-reports/*.txt -``` - -### 添加新安全模块 - -每个安全模块遵循统一的约定: - -1. 在 `com.aluer.security` 包下创建新类 -2. 通过构造器注入 `ServerGuardConfig` 获取配置 -3. 实现 `getPosture()` 方法返回态势数据(供 Kernel 消费) -4. 在 `NetworkThreatFusionService` 中注册(如果模块涉及网络安全) -5. 在 `AluerOperationsCenterService` 的 `buildOverview()` 中聚合(如果需要展示到控制台) -6. 在 `application.yml` 中添加对应的配置节点 - ---- - -## ❓ 常见问题 - -
-如何验证 AI 是否正常工作? - -```bash -# 在终端执行 -aluer> ask 你好 -``` - -如果有 AI 回复,说明 DeepSeek 配置正确。也可以查看日志: - -```bash -tail -f /var/log/serverguard.log | grep DeepSeek -``` -
- -
-收不到邮件告警? - -1. 确认 `application.yml` 中邮箱配置的 `username`/`password` 正确 -2. QQ 邮箱必须使用**授权码**而非登录密码 -3. 检查垃圾邮件文件夹 -4. 执行 `alert test` 发送测试邮件确认 - -```bash -aluer> alert test -``` -
- -
-首次部署应该注意什么? - -建议先开启 **dry-run 模式**: - -```yaml -serverguard: - security: - host-enforcement: - dry-run: true # 本机防火墙仅记录不执行 - cloud-edge: - dry-run: true # Cloudflare 仅记录不执行 - self-healing: - dry-run: true # 自愈仅记录不执行 -``` - -观察 1-2 天确认无误报后,再逐步关闭 dry-run。 -
- -
-如何查看运行日志? - -```bash -# systemd 管理时 -sudo journalctl -u serverguard -f - -# 直接运行时查看应用日志 -tail -f /var/log/serverguard.log - -# 查看 Minecraft 日志 -tail -f /opt/minecraft/logs/latest.log -``` -
- -
-如何升级到新版本? - -```bash -# 1. 停止服务 -sudo systemctl stop serverguard - -# 2. 备份当前版本和数据 -cp /opt/serverguard/serverguard.jar /opt/serverguard/serverguard.jar.bak -cp -r /opt/serverguard/backups /backup/ - -# 3. 替换 jar 包 -cp target/serverguard.jar /opt/serverguard/ - -# 4. 重启服务 -sudo systemctl start serverguard - -# 5. 验证 -sudo systemctl status serverguard -curl http://localhost:8080/api/status -``` -
- -
-如何安全地修改配置? - -1. 不要直接编辑 jar 包内的 `application.yml` -2. 在 jar 包同目录创建外部 `application.yml`(Spring Boot 自动优先读取外部文件) -3. 或者通过环境变量覆盖(推荐生产环境) -4. 修改后重启服务 - -```bash -# 方法 1:外部配置文件 -sudo nano /opt/serverguard/application.yml -sudo systemctl restart serverguard - -# 方法 2:环境变量(在 systemd unit 中设置) -sudo systemctl edit serverguard -# 添加: -# [Service] -# Environment="DEEPSEEK_API_KEY=sk-xxx" -sudo systemctl restart serverguard -``` -
- -
-为什么有两个决策引擎(Sovereign + Kernel)?不会冲突吗? - -不会。它们是互补关系: - -- **Sovereign(DeepSeek)** 擅长理解复杂的、从未见过的攻击模式,但延迟 2-5 秒且偶有非结构化输出 -- **Kernel(规则引擎)** 响应时间 < 1ms,100% 可预测,但无法应对未知攻击模式 - -当两者输出不一致时,`AIAutonomousService`(L3)按照 `autonomy.deepseek-dominant` 配置决定谁来拍板。同时 `SecurityOrchestrationService` 做最终的安全兜底——任何操作都不会超过 `max-actions-per-hour` 的限制。 -
- -
-性能开销有多大? - -在 2 核 4GB 的 VPS 上实测: - -- JVM 常驻内存:约 180-250 MB(含 Spring Boot + 所有服务) -- CPU 空闲占用:< 2%(监控和 Pulse 循环) -- DeepSeek API 调用时 CPU 开销:约 5%(网络 I/O 等待为主) -- 不影响 Minecraft 服务端性能(通过 RCON 异步通信) -
- ---- - -## 📄 许可证 - -本项目基于 **Apache License 2.0** 开源。完整许可证文本见 [LICENSE](LICENSE) 文件。 - -| 条款 | 说明 | -|:-----|:-----| -| ✅ **允许** | 商业使用、修改、分发、专利授权、私人使用 | -| ⚠️ **条件** | 分发时需包含许可证声明和版权声明,修改文件需标注变更 | -| ❌ **限制** | 不提供任何担保,作者不对使用本软件造成的损失承担责任 | - ---- - -## 🌟 支持项目 - -如果 Aluer ServerGuard 帮助了你,请考虑: - -

- 收藏 -   - 复刻 -   - 报告问题 -   - 讨论 -

- ---- - -

🏆 贡献者

- -

- - - -

- -

- 由 Aluer 社区用 ❤️ 构建 — 守护世界各地的 Minecraft 服务器 -

- ---- - -

- - 仓库大小 - - - 许可证 - - 技术栈 -
- Aluer ServerGuard v3.0 — 为你的 Minecraft 社区提供自主防护 -

+Proprietary. All rights reserved. diff --git a/README_EN.md b/README_EN.md index e9747f6..c4c73b1 100644 --- a/README_EN.md +++ b/README_EN.md @@ -1,1197 +1,1086 @@ -
+# Aluer ServerGuard V5.0 -**简体中文** · [**English**](README.md) - -
- -
- - - - - -
- -

- Java - Spring Boot - React - Vite - DeepSeek AI - License -

- -

- Stars - Forks - Issues - PRs - Last Commit -

+> AI-Powered Comprehensive Protection System for Minecraft PaperMC Servers --- -

- - Aluer ServerGuard - -

+## Project Overview -

- 🛡️ AI-Powered Minecraft PaperMC Server Security & Automation Platform -

+Aluer ServerGuard is a next-generation intelligent security protection system designed for Minecraft PaperMC servers. The system features an **Agent architecture** with a lightweight Paper plugin serving as the data collection frontend, paired with an external Spring Boot analysis engine, delivering comprehensive real-time server protection. -

- Built with ❤️ for Minecraft server operators who refuse to compromise on security -

- -
-

- "In a world where DDoS attacks, bot swarms, and zero-day exploits threaten your Minecraft community,
Aluer stands as the autonomous guardian — powered by DeepSeek AI and a multi-layer kernel fusion engine."
-

-
- -

- 🏗 Architecture  ·  - 🚀 Quick Start  ·  - ⚙️ Config  ·  - 📦 Modules  ·  - 🌐 API  ·  - 🖥 Console  ·  - 💻 Commands  ·  - ❓ FAQ -

- -
- - - - - - - - - -
-
- 2-5s
- LLM Response -
-
- <1ms
- Kernel Latency -
-
- 4-Tier
- Defense Levels -
-
- 85+
- Security Modules -
-
- ~200MB
- Memory Footprint -
- -
- -## Table of Contents - -- [System Architecture](#-system-architecture) - - [Three-Layer Decision Engine](#1-three-layer-decision-engine) - - [Kernel Signal Fusion Model](#2-kernel-signal-fusion-model) - - [Data Flow Overview](#3-data-flow-overview) -- [Quick Start](#-quick-start) - - [Requirements](#requirements) - - [Build](#build) - - [Environment Variables](#environment-variables) - - [First Launch](#first-launch) - - [One-Click Install](#one-click-install) -- [Deployment Guide](#-deployment-guide) - - [Systemd Services](#systemd-services) - - [sudo Configuration](#sudo-configuration) - - [Reverse Proxy](#reverse-proxy-optional) -- [Configuration Reference](#-configuration-reference) - - [Full Config Tree](#full-config-tree) - - [Environment Variable Injection](#environment-variable-injection-table) -- [Module Catalog](#-module-catalog) - - [AI Decision Layer](#ai-decision-layer-comaluerai) - - [Kernel Engine Layer](#kernel-engine-layer-comaluerkernel) - - [Security Defense Layer](#security-defense-layer-comaluersecurity) - - [Operations Control Layer](#operations-control-layer-comaluerconsole) - - [Monitoring Collection Layer](#monitoring-collection-layer-comaluermonitor) - - [Core Service Layer](#core-service-layer-comaluerservice) - - [Web Interaction Layer](#web-interaction-layer-comaluerweb) - - [Notification & Reporting Layer](#notification--reporting-layer-comaluernotification) - - [Auxiliary Modules](#auxiliary-modules) - - [Data Models](#data-models-comaluermodel) -- [Defense Levels & Auto Response](#️-defense-levels--auto-response) -- [API Reference](#-api-reference) - - [System Status API](#system-status-api) - - [Security Posture API](#security-posture-api) - - [Health Check API](#health-check-api) - - [Notification & Report API](#notification--report-api) - - [Console Operations API](#console-operations-api) - - [SSH Gateway API](#ssh-gateway-api) - - [Backup Management API](#backup-management-api) -- [Web Console](#-web-console) -- [Shell Command Reference](#-shell-command-reference) -- [Developer Guide](#-developer-guide) -- [FAQ](#-faq) -- [License](#-license) -- [Support](#-support) +Key Features: +- **AI Behavioral Analysis**: Anomaly detection based on Isolation Forest and time series prediction +- **DeepSeek LLM Integration**: Automated security alert analysis and defense strategy generation +- **Full Anti-Cheat Coverage**: Countermeasures against every hack module in Meteor Client and similar cheat clients +- **Server Self-Healing**: Automatic recovery from TPS/CPU/Memory anomalies, built-in DDoS defense +- **Dual-Mode Deployment**: Plugin embedded mode and External monitoring mode +- **135+ Security Modules**: Covering anti-cheat, network security, host security, intrusion detection, and forensic analysis --- -## ✨ Why Aluer? +## Version History - - - - - - - - - -
-

🧠 Dual-Engine Intelligence

-

LLM (DeepSeek) + Kernel Rule Engine working in tandem. Sovereign handles unknown threats; Kernel reacts in <1ms for known patterns. No single point of decision failure.

-
-

🛡️ Full-Stack Defense

-

From Minecraft protocol layer → Application WAF → OS firewall → Cloudflare edge. 85+ security modules covering L3-L7, zero-trust architecture, and honeypot deception.

-
-

📊 Real-Time Visualization

-

React 19 Nebula Console with SSE live streaming, performance sparklines, health probes, auto-refresh — designed for incident commanders who need instant clarity.

-
-

🔧 Autonomous Operations

-

Self-healing orchestration, auto-backup before recovery, scheduled tasks, Discord/Slack webhooks, and HTML attack reports. Your server guards itself while you sleep.

-
+| Version | Date | Key Updates | +|---------|------|-------------| +| V5.3 | 2026-05 | Meteor Client world/player/misc countermeasures: SpeedMine, FastUse, NoInteract, AutoMine, VeinMiner, AutoTool, FakePlayer, PistonAura, Anchor, StashFinder | +| V5.2 | 2026-05 | Meteor Client movement countermeasures: NoSlow, Spider, Step, PacketFly, AirJump, LongJump, AntiHunger, FastFall, VClip | +| V5.1 | 2026-05 | Meteor Client combat countermeasures: Criticals, AutoTotem, Surround, AutoTrap, AutoCrystal, AutoArmor, ChestSwap, AutoLog, Hitboxes, BowAimbot | +| V5.0 | 2026-04 | Agent architecture refactoring, WebSocket real-time communication, Timer/Velocity/Phase/Blink/FastBreak/ElytraFly anti-cheat | +| V4.0 | 2026-03 | KillAura/Reach/Speed/Jesus/NoFall/Scaffold/Nuker/AutoClicker anti-cheat, player behavior, server protection | --- -## 🧬 System Architecture - -Aluer ServerGuard deploys on the same host as your Minecraft server, communicating with PaperMC via the **RCON protocol** while managing OS-level firewalls (iptables/ufw) and Cloudflare edge protection. - -### 1. Three-Layer Decision Engine - -This is the core design — L1 handles strategic decisions, L2 handles signal-level tactical judgment, and L3 handles execution. +## Architecture ``` -┌──────────────────────────────────────────────────────────────┐ -│ L1: AluerSovereignEngine │ -│ Input: Full-network posture JSON (compressed context) │ -│ Process: Send to DeepSeek LLM for structured directives │ -│ Output: workflow (1 of 8) + defenseLevel + reason │ -│ Cycle: Every 45 seconds │ -│ Trait: LLM-driven, natural language reasoning, handles │ -│ novel/ambiguous threat patterns │ -├──────────────────────────────────────────────────────────────┤ -│ L2: AluerKernelEngine │ -│ Input: Real-time signals from 5 virtual modules │ -│ Process: Weighted aggregation → 3D pressure → directives │ -│ Output: heat / resonance / control + KernelDirective │ -│ Cycle: Every 30 seconds (Pulse) │ -│ Trait: Deterministic rules, explainable, immune to │ -│ LLM latency/hallucination │ -├──────────────────────────────────────────────────────────────┤ -│ L3: AIAutonomousService │ -│ Input: L1 macro directive + L2 Kernel directive │ -│ Process: Conflict arbitration → cooldown → rate-limit │ -│ Output: ban-ip / kick / whitelist / clear-lag │ -│ Guard: Max 12 actions/hour, dual-signal for high-risk ops │ -└──────────────────────────────────────────────────────────────┘ ++---------------------------------------------------------------------+ +| Aluer ServerGuard System Architecture | ++---------------------------------------------------------------------+ +| | +| +------------------+ WebSocket +----------------+ | +| | PaperMC Server | <========================> | ServerGuard | | +| | | ws://host:8080/agent | Spring Boot | | +| | +------------+ | | +----------+ | | +| | | AluerPlugin| | EVENT ---------------> | | Security | | | +| | | (Agent) | | METRICS --------------> | | Modules | | | +| | | | | ALERT -----------------> | | (135+) | | | +| | | Bukkit | | HEARTBEAT -------------> | +----------+ | | +| | | Events | | | +----------+ | | +| | +------------+ | <-------- COMMAND ----- | | ML/AI | | | +| | | <-------- CONFIG ------ | | Engine | | | +| | Event Listeners | | +----------+ | | +| | + Combat | | +----------+ | | +| | + Block | | | DeepSeek | | | +| | + Movement | | | Analysis | | | +| | + Inventory | | +----------+ | | +| | + Chat | | +----------+ | | +| | + Command | | | Web | | | +| | + Entity | | | Dashboard | | | +| | + Packet | | +----------+ | | +| | + World | +----------------+ | +| +------------------+ | | +| | | +| +------------v-------+ | +| | Self-Healing | | +| | Shield / Kernel | | +| | Autonomy Engine | | +| +--------------------+ | ++---------------------------------------------------------------------+ ``` -**Why two decision layers?** Sovereign (DeepSeek) excels at understanding novel threats but has API latency (~2-5s) and occasional unstructured output. Kernel is a pure rule engine with <1ms latency, capable of instant reaction to known threat patterns. The two layers intersect and back each other up. +**Communication Protocol**: All messages are single-line JSON transmitted via WebSocket text frames in both directions. -### 2. Kernel Signal Fusion Model +Agent-to-Server message types: +- `EVENT` -- Bukkit event data (player movement, combat, block operations, etc.) +- `METRICS` -- Server metrics (TPS, CPU, Memory, online player count) +- `ALERT` -- Security alerts +- `HEARTBEAT` -- Keep-alive heartbeat +- `HANDSHAKE` -- Initial connection handshake +- `COMMAND_RESULT` -- Command execution acknowledgment -The Kernel runs 5 virtual modules (`KernelModule` interface), each collecting pressure signals from specific security subsystems: +Server-to-Agent command types: +- `COMMAND` -- Execute action (BAN_IP, BAN_PLAYER, KICK, CLEAR_LAG, etc.) +- `CONFIG` -- Dynamic configuration update +- `SHUTDOWN` -- Close connection -| Module | Name | Data Source | Vector | Baseline Weight | -|--------|------|-------------|--------|-----------------| -| `ThreatMeshModule` | Threat Mesh | DDoS / Firewall / IDS / Port Scan / DPI | `network` | 1.12 | -| `CommandLatticeModule` | Command Lattice | Command Guard (dangerous cmd + RCON brute force) | `command` | 1.18 | -| `HardeningMatrixModule` | Hardening Matrix | Security baseline audit (vuln × severity) | `integrity` | 1.05 | -| `PerimeterWardModule` | Perimeter Ward | WAF (blocked/suspicious + active clients) | `perimeter` | 0.92 | -| `EchoGridModule` | Echo Grid | Historical IP pressure memory decay | `memory` | 0.84 | +--- -Each Pulse cycle (default 30s), 5 modules produce 0~N `KernelSignal` objects. Aggregation algorithm: +## Technology Stack -``` -For each signal: - weighted = clamp(pressure × adaptiveWeight[module], 0, 100) - vectorScores[vector] += weighted - moduleScores[module] += weighted +| Technology | Version | Purpose | +|------------|---------|---------| +| Java | 21 | Core language | +| Spring Boot | 3.2.0 | Application framework | +| Maven | 3.9.6 | Build management | +| PaperMC API | 1.21.1-R0.1-SNAPSHOT | Minecraft server API | +| Spring WebSocket | 3.2.0 | Agent communication | +| Spring Mail | 3.2.0 | Email alerts | +| Spring Shell | 3.1.3 | CLI interaction | +| SnakeYAML | 2.2 | YAML configuration | +| Smile | 2.6.0 | Machine learning algorithms | +| Apache Commons Math | 3.6.1 | Math/statistics | +| Gson | (embedded) | JSON serialization | -heat = clamp(peak_vector × 0.68 + avg_vector × 0.32, 0, 100) -resonance = clamp(heat × 0.45 + second_vector × 0.18 + energized × 14 + count × 2.2, 0, 100) -control = clamp(100 - heat × 0.62 - resonance × 0.28, 0, 100) +--- + +## Complete Security Module Inventory + +### I. Anti-Cheat -- Combat (15 modules) + +| Module | Hack Detected | Detection Method | +|--------|---------------|------------------| +| AntiKillAuraService | KillAura | Multi-target switching, aimbot angle consistency, max-range attack patterns | +| AntiReachService | Reach | Attack distance validation, position backtracking | +| AntiSpeedService | Speed | Horizontal movement speed anomaly analysis | +| AntiCriticalsService | Criticals | Zero-velocity crits, no-jump crits, crit rate statistics | +| AntiAutoCrystalService | AutoCrystal | Crystal placement/detonation speed, optimal position calculation detection | +| AntiAutoTotemService | AutoTotem | Totem re-equip speed (ms-level), consecutive totem usage pattern | +| AntiSurroundService | Surround | Four-direction block placement speed, defensive block pattern recognition | +| AntiAutoTrapService | AutoTrap | Target player cage construction speed, piston trap automation | +| AntiAutoArmor | AutoArmor | Multi-slot armor switching speed, backpack scan pattern | +| AntiChestSwap | ChestSwap | Chestplate/elytra swap tick-level detection | +| AntiAutoLog | AutoLog | Post-damage disconnect pattern, low-HP disengagement detection | +| AntiHitboxes | Hitboxes | Edge hit rate, ray trace distance distribution analysis | +| AntiBowAimbot | BowAimbot | Moving target hit rate, trajectory consistency, instant precision | +| AntiVelocityService | Velocity | Knockback magnitude anomaly, anti-knockback detection | +| AntiAutoClickerService | AutoClicker | CPS statistics, click interval entropy analysis | + +### II. Anti-Cheat -- Movement (18 modules) + +| Module | Hack Detected | Detection Method | +|--------|---------------|------------------| +| AntiFlyDetectionService | Fly | Vertical/horizontal velocity, hover duration, movement pattern analysis | +| AntiJesusService | Jesus | Water/lava surface movement validation | +| AntiNoFallService | NoFall | Landing detection, fall damage validation | +| AntiSpeedService | Speed | Horizontal movement speed anomaly analysis | +| AntiTimerService | Timer | Game tick interval anomaly, movement speed frequency analysis | +| AntiPhaseService | Phase | Block clipping/penetration detection, solid block pass-through validation | +| AntiBlinkService | Blink | Rapid disconnect damage evasion detection | +| AntiSpiderService | Spider | Non-climbable block wall movement, vertical wall movement detection | +| AntiStepService | Step | Full-block step-up without jump detection | +| AntiNoSlowService | NoSlow | Item-use movement speed detection (eating/bow/shield) | +| AntiPacketFlyService | PacketFly | Packet manipulation flight, oscillation patterns, never-landing detection | +| AntiAirJumpService | AirJump | Mid-air jump packet detection, consecutive aerial jumps | +| AntiLongJump | LongJump | Extreme horizontal jump distance detection | +| AntiAntiHunger | AntiHunger | Zero hunger consumption under high activity detection | +| AntiFastFall | FastFall | Above-terminal-velocity falling detection | +| AntiVClip | VClip | Instant vertical block penetration (excluding legitimate teleport) | +| AntiElytraFlyService | ElytraFly | Elytra speed/altitude manipulation detection | +| AntiScaffoldService | Scaffold | Block placement frequency/angle/speed pattern analysis | + +### III. Anti-Cheat -- World/Player/Misc (19 modules) + +| Module | Hack Detected | Detection Method | +|--------|---------------|------------------| +| AntiNukerService | Nuker | Mining speed/range/pattern recognition | +| AntiAutoMineService | AutoMine | Automated mining behavior detection | +| AntiSpeedMineService | SpeedMine | Accelerated mining (InstaMine/PacketMine) detection | +| AntiFastBreakService | FastBreak | Block breaking speed anomaly detection | +| AntiFastUseService | FastUse | Item use acceleration detection | +| AntiNoInteractService | NoInteract | Interaction bypass detection | +| AntiVeinMinerService | VeinMiner | Automated vein mining pattern detection | +| AntiAutoTool | AutoTool | Instant tool switching detection | +| AntiAutoFishService | AutoFish | Fishing behavior timing/reaction speed analysis | +| AntiChestStealService | ChestSteal | Container open/loot speed pattern recognition | +| AntiInventoryManipulationService | InventoryManipulation | Inventory operation speed, illegal slot operation detection | +| AntiBaritoneService | Baritone | Path smoothness/behavior repetition analysis | +| AntiXrayDetectionService | Xray | Diamond ratio/straight-line mining/dark-precision detection | +| AntiGriefDetectionService | Grief | Block destruction rate/TNT/arson/chest theft detection | +| AntiFakePlayer | FakePlayer | Fake player entity detection | +| AntiPistonAura | PistonAura | Piston trap automation detection | +| AntiAnchor | Anchor | Hole anchor defense detection | +| AntiStashFinder | StashFinder | Automated storage cache scanning detection | +| AntiDupeDetectionService | AntiDupe | Item duplication detection (stack anomaly, 9 duplication methods) | + +### IV. Server Exploit Protection (12 modules) + +| Module | Protection Target | +|--------|-------------------| +| AntiSignExploitService | Sign NBT exploits (oversized JSON, invalid components, NBT bombs) | +| AntiBookBanService | Book ban exploits (oversized pages, deep JSON nesting) | +| AntiResourcePackExploitService | Resource pack exploits (malicious URLs, oversized files, format validation) | +| AntiTabCompleteCrashService | Tab-complete crash (long text, deep nesting completion limits) | +| AntiOfflineModeSpoofService | Offline UUID spoofing (premium UUID conflicts, IP correlation) | +| CrashExploitProtectionService | Crash exploit protection (oversized packets, NBT bombs, book attacks) | +| CrashExploitSignatureDB | Crash exploit signature database (12 known signatures) | +| LagMachineDetectionService | Lag machine detection (observer chains, TNT stacks, redstone density) | +| ChunkLoadRateLimiter | Chunk load rate limiting (WARN/LIMIT/BLOCK 3-tier response) | +| EntityCountEnforcer | Entity count enforcement (per-chunk/player/type auto-removal) | +| RedstoneUpdateLimiter | Redstone update frequency limiting (degrade/freeze/exponential backoff) | +| PacketFloodProtectionService | Packet flood protection | + +### V. Chat & Social Security (5 modules) + +| Module | Protection Target | +|--------|-------------------| +| ChatFloodProtectionService | Chat flood (frequency, similarity, length surges) | +| AntiAdvertisementService | Advertisement detection (IP/domain/group ID regex) | +| AntiPhishingLinkService | Phishing links (suspicious domains, short links, SSL verification) | +| AntiCommandAbuseService | Command abuse (rate limiting, sensitive command interception) | +| PlayerPrivacyService | Player privacy (IP anonymization, coordinate hiding, log anonymization) | + +### VI. Network Security (13 modules) + +| Module | Protection Target | +|--------|-------------------| +| DDoSProtectionService | DDoS attacks (SYN/UDP/ICMP/HTTP/Slow connection/Amplification) | +| DDoSDefenseCoordinator | Multi-layer DDoS defense orchestration | +| ProtocolStateValidator | Protocol state machine (HANDSHAKE/STATUS/LOGIN/PLAY transitions) | +| BotFingerprintDetector | Bot fingerprint (login timing, naming patterns, movement entropy) | +| NBTExploitPrevention | NBT exploit prevention (depth/size limits) | +| ConnectionHandshakeValidator | Handshake validation (protocol version, hostname, ping flood, port scan) | +| PortScanDetectionService | Port scan detection | +| BruteForceProtectionService | Brute force protection (multi-window detection) | +| AntiVPNProxyService | VPN/proxy detection (known VPN IP database, hosting ASN matching) | +| DNSTunnelDetectionService | DNS tunnel detection (entropy, Base32 encoding, suspicious TLDs) | +| ReverseShellDetectionService | Reverse shell detection (50+ shell pattern matching) | +| ProcessInjectionDetectionService | Process injection detection | +| ARPSpoofDetectionService | ARP spoofing detection (MAC changes, gateway forgery) | + +### VII. Host & Access Control Security (6 modules) + +| Module | Protection Target | +|--------|-------------------| +| FileIntegrityMonitorService | File integrity monitoring (hash baseline, real-time monitoring) | +| BackdoorPluginScannerService | Backdoor plugin scanning (known malicious class names, remote execution) | +| ConfigTamperDetectionService | Configuration tampering detection (ops/whitelist real-time monitoring) | +| OPPrivilegeMonitorService | OP privilege monitoring (privilege changes, sensitive command auditing) | +| AntiAltAccountService | Alt account detection (IP correlation, behavioral similarity, login patterns) | +| AntiNameSpoofService | Name spoofing detection (admin/famous player nickname forgery) | + +### VIII. Advanced Security Infrastructure (28 modules) + +| Module | Function | +|--------|----------| +| PlayerSessionValidationService | Player session validation (UUID forgery, premium/offline detection) | +| PluginVerificationService | Plugin integrity verification (hash comparison, unauthorized modification) | +| BackupIntegrityService | Backup integrity verification (SHA-256, file count, size comparison) | +| ConnectionThrottleService | Connection rate limiting (IP/time window/incremental delay) | +| GeoBlockService | Geographic IP blocking (country/region filtering) | +| AntiSkinSpoofService | Skin spoofing detection (model data anomaly, skin URL detection) | +| JwtAuthService | JWT authentication and token management | +| AntiBotDetectionService | Anti-bot detection (name, join rate, IP correlation) | +| CSPEnforcementService | CSP security header enforcement (8 response headers) | +| SSRFProtectionService | SSRF protection (internal IP, cloud metadata, protocol restrictions) | +| XXEProtectionService | XXE protection (entity injection, Billion Laughs detection) | +| DatabaseFirewallService | Database firewall (SQL injection, UNION queries, time-based blind) | +| DataLossPreventionService | Data loss prevention (12 sensitive info rules, auto-masking) | +| MemoryProtectionService | JVM memory protection (heap/GC/memory leak detection) | +| SecureFileDeletionService | Secure file deletion (multi-pass overwrite, DoD standard) | +| ForensicsCollectorService | Forensic collection (process/network/log snapshots) | +| IncidentResponseService | Incident response (5 predefined response playbooks) | +| ThreatHuntingService | Threat hunting (10 hunt definitions, 5 categories) | +| ComplianceScannerService | Compliance scanning (7 categories, 20+ checks) | +| ExploitSignatureService | Exploit signature detection (Log4Shell, SQLi, RCE -- 15 types) | +| SecurityOrchestrationService | Multi-layer defense orchestration | +| SecurityAutomationScheduler | Security automation scheduling | +| HostEnforcementService | Host-level enforcement | +| HostIntrusionCountermeasureService | Host intrusion countermeasures | +| IntrusionDetectionService | Network intrusion detection | +| IntrusionPreventionSystem | Network intrusion prevention | +| WebApplicationFirewall | Web application firewall | +| ZeroTrustArchitectureService | Zero-trust architecture | + +### IX. Network & Traffic Analysis (10 modules) + +| Module | Function | +|--------|----------| +| NetworkMonitorService | Network traffic monitoring | +| NetworkSnifferService | Network packet sniffing | +| NetworkThreatFusionService | Multi-source threat intelligence fusion | +| FlowAnalyzerService | Traffic behavior analysis | +| TrafficAnalysisService | Traffic pattern analysis | +| TrafficShapingService | Traffic shaping and QoS | +| PacketInspectionService | Deep packet inspection | +| ProtocolAnalysisService | Protocol anomaly analysis | +| TokenBucketRateLimiter | Reusable token bucket rate limiting primitive | +| FirewallService | System firewall management | + +### X. Infrastructure & Operations Security (8 modules) + +| Module | Function | +|--------|----------| +| SIEMService | Security information and event management | +| LogAnalysisService | Log pattern analysis | +| LogCorrelationService | Cross-source log correlation | +| ThreatIntelligenceService | Threat intelligence aggregation | +| IPReputationService | IP reputation database queries | +| SSLTLSCertificateService | SSL/TLS certificate management | +| SecurityBaselineHardeningService | Security baseline hardening | +| ContainerSecurityService | Container runtime security | + +### XI. ML/AI Behavioral Analysis (4 modules) + +| Module | Function | +|--------|----------| +| BehavioralProfilingEngine | Player behavioral profiling (statistical baseline modeling) | +| CombatPatternRecognizer | Combat pattern recognition (anomalous combat sequence detection) | +| MovementPatternAnalyzer | Movement pattern analysis (trajectory anomalies, path entropy) | +| ThreatScoreAggregator | Threat score aggregation (multi-dimensional threat fusion and escalation) | + +--- + +## Deployment Guide + +### Mode 1: Plugin Embedded Mode (Recommended) + +ServerGuard runs directly inside the Minecraft server process as a Paper plugin, achieving zero network latency and maximum real-time performance. + +**Prerequisites:** +- Minecraft PaperMC 1.21.1 server installed +- Java 21 runtime +- ServerGuard engine JAR compiled + +**Deployment Steps:** + +1. **Build the plugin** + ```bash + cd /opt/AluerIII + ./apache-maven-3.9.6/bin/mvn package -DskipTests + ``` + +2. **Install plugin to Minecraft server** + ```bash + cp target/serverguard-4.0.0.jar /opt/minecraft/plugins/AluerServerGuard.jar + ``` + +3. **Create plugin config** at `plugins/AluerServerGuard/config.yml`: + ```yaml + server-url: ws://localhost:8080/agent + ``` + +4. **Start ServerGuard engine** (must start before Minecraft server) + ```bash + java -jar target/serverguard-4.0.0.jar + ``` + +5. **Start Minecraft server** + ```bash + cd /opt/minecraft + java -Xms4G -Xmx4G -jar paper-1.21.11.jar + ``` + +Upon startup, AluerPlugin will automatically connect to the ServerGuard engine via WebSocket and begin pushing Bukkit event data. + +### Mode 2: External Monitoring Mode + +ServerGuard runs as an independent process, providing external protection via RCON and log monitoring. Suitable for scenarios where plugin installation is not desired. + +**Deployment Steps:** + +1. **Build** + ```bash + ./apache-maven-3.9.6/bin/mvn package -DskipTests + ``` + +2. **Configure `application.yml`** + ```yaml + serverguard: + mode: external + minecraft: + working-dir: /opt/minecraft + rcon: + enabled: true + host: localhost + port: 25575 + password: "your_rcon_password_here" + process-name: paper-1.21.11.jar + ``` + +3. **Enable RCON in Minecraft `server.properties`** + ```properties + enable-rcon=true + rcon.port=25575 + rcon.password=your_rcon_password_here + ``` + +4. **Start ServerGuard** + ```bash + java -jar target/serverguard-4.0.0.jar + ``` + +--- + +## Configuration Reference + +### Core Configuration (serverguard.*) + +```yaml +serverguard: + mode: ${SERVERGUARD_MODE:external} # plugin or external + + minecraft: + service-name: minecraft + process-name: paper-1.21.11.jar + jar-file: paper-1.21.11.jar + working-dir: /opt/minecraft + java-opts: -Xms4G -Xmx4G + check-interval-seconds: 5 + rcon: + enabled: true + host: localhost + port: 25575 + password: ${RCON_PASSWORD:} + + monitor: + tps-threshold: 15 # Alert when TPS falls below this value + cpu-threshold: 80.0 # Alert when CPU usage exceeds this value (%) + memory-threshold: 85.0 # Alert when memory usage exceeds this value (%) + connection-threshold: 50 # Alert when concurrent connections exceed this value + log-watch-lines: 100 # Number of log lines to monitor + log-path: /opt/minecraft/logs/latest.log + + alert: + enabled: true + email: + smtp-host: smtp.qq.com + smtp-port: 587 + username: ${ALUER_ALERT_SMTP_USERNAME:} + password: ${ALUER_ALERT_SMTP_PASSWORD:} + to: + - ${ALUER_ALERT_EMAIL_PRIMARY:} + - ${ALUER_ALERT_EMAIL_SECONDARY:} + rate-limit: + per-type-seconds: 300 # Minimum interval between same-type alerts (seconds) + max-emails-per-minute: 10 # Maximum emails per minute ``` -Adaptive weights via exponential moving average: +### AI Configuration (serverguard.ai.*) -``` -target = baseline + (pressure ≥ 80 ? 0.18 : pressure ≥ 55 ? 0.08 : 0) -active = current × 0.82 + target × 0.18 -active = clamp(active, 0.72, 1.45) +```yaml + ai: + enabled: true + use-isolation-forest: true # Enable Isolation Forest anomaly detection + use-prediction: true # Enable time series prediction + sliding-window-size: 100 # Analysis sliding window size + anomaly-threshold: 0.7 # Anomaly detection threshold (0-1) + prediction-horizon-minutes: 60 # Prediction horizon (minutes) + deepseek: + enabled: true + api-key: ${DEEPSEEK_API_KEY:} + base-url: ${DEEPSEEK_BASE_URL:https://api.deepseek.com} + model: ${DEEPSEEK_MODEL:deepseek-chat} + max-tokens: 1000 + temperature: 0.35 # Analysis stability (0=precise, 1=creative) + auto-analyze-alerts: true # Automatically analyze alerts + analysis-interval-seconds: 45 # Analysis interval (seconds) + auto-execute: + enabled: true + ban-ip: true # Allow automatic IP banning + kill-entity: true # Allow automatic entity cleanup + clear-lag: true # Allow automatic lag clearing + set-spawn-rate: true # Allow automatic spawn rate adjustment + kick-player: true # Allow automatic player kicking + whitelist: true # Allow automatic whitelist enabling + min-confidence: 88 # Minimum confidence for auto-execution (%) ``` -EchoGrid (attacker memory) decay: +### Security Configuration (serverguard.security.*) -``` -cell.pressure = cell.pressure × 0.55 + pulse.heat × 0.75 -// Cells exceeding retention time are auto-purged +```yaml + security: + enabled: true + auto-ban-vpn: true + check-on-login: true + max-connections-per-ip: 3 # Maximum connections per IP + block-common-exploits: true + log-all-commands: true + + minecraft-defense: + enabled: true + game-tcp-port: 25565 + query-udp-port: 25565 + rcon-tcp-port: 25575 + status-ping-threshold: 25 # Status ping flood threshold + login-burst-threshold: 12 # Login burst threshold + bot-swarm-threshold: 15 # Bot swarm threshold + query-flood-threshold: 30 # Query flood threshold + rcon-brute-force-threshold: 5 # RCON brute force threshold + compression-payload-threshold: 8192 # Compression payload maximum + + ddos-defense: + enabled: true + syn-flood-threshold: 100 + udp-flood-threshold: 200 + icmp-flood-threshold: 100 + http-flood-threshold: 150 + slow-connection-threshold: 150 + amplification-threshold: 20 + minecraft-status-threshold: 20 + minecraft-login-threshold: 10 + minecraft-rcon-threshold: 5 + minecraft-query-threshold: 25 + minecraft-bot-swarm-threshold: 12 + + anti-intrusion: + enabled: true + monitor-commands: true + monitor-processes: true + monitor-files: true + monitor-plugins: true + monitor-systemd: true + monitor-rcon: true + file-integrity: + enabled: true + max-depth: 5 + monitored-paths: + - /opt/minecraft/plugins + - /opt/minecraft/server.properties + - /opt/minecraft/paper-1.21.11.jar + - /opt/minecraft/start.sh + - /etc/systemd/system/minecraft.service + + host-enforcement: + enabled: true + dry-run: true # Dry-run mode (no actual blocking) + preferred-backend: auto # Backend: auto/iptables/nftables/firewalld + default-block-minutes: 60 # Default block duration (minutes) + default-rate-limit-per-minute: 120 # Default rate limit per minute + mirror-to-cloud-edge: true # Mirror to cloud edge + + cloud-edge: + enabled: false + dry-run: true + provider: cloudflare + zone-id: ${ALUER_CLOUDFLARE_ZONE_ID:} + api-key: ${ALUER_CLOUDFLARE_API_KEY:} + api-email: ${ALUER_CLOUDFLARE_EMAIL:} + default-block-mode: block + default-challenge-mode: challenge + enable-under-attack-on-critical: true + + orchestration: + enabled: true + allow-local-block: true + allow-edge-challenge: true + allow-minecraft-defense: true + notify-on-critical: true + + automation: + enabled: true + feed-refresh-minutes: 15 # Threat intel refresh interval + posture-snapshot-minutes: 5 # Security posture snapshot interval + integrity-rescan-minutes: 30 # Integrity rescan interval + rule-sync-minutes: 10 # Rule sync interval + incident-retention-minutes: 120 # Incident retention period + + autonomy: + enabled: true + deepseek-dominant: true # DeepSeek-dominant decision making + quiet-console: true # Quiet console mode + loop-interval-seconds: 45 # Autonomy loop interval + min-risk-score-for-action: 70 # Minimum risk score for action + critical-risk-score: 90 # Critical risk score + workflow-cooldown-seconds: 180 # Workflow cooldown + max-actions-per-hour: 12 # Maximum actions per hour + require-second-signal-for-containment: true # Require second signal for containment + + shield: + enabled: true + auto-mode: true + auto-enable-under-attack: true + heat-trigger: 78 # Heat trigger threshold + resonance-trigger: 72 # Resonance trigger threshold + threat-score-trigger: 85 # Threat score trigger threshold + edge-challenge-offender-limit: 6 # Edge challenge offender limit + shelter-rate-limit-per-minute: 45 # Shelter rate limit per minute + attacker-notice-enabled: true + deterrence-message: "Your source has been identified, recorded, and isolated by Aluer." + + kernel: + enabled: true + pulse-interval-seconds: 30 # Pulse interval + pulse-history-size: 180 # Pulse history size + journal-size: 300 # Journal size + echo-retention-minutes: 180 # Echo retention period + adaptive-weights: true # Adaptive weights + directive-heat-threshold: 60 # Directive heat threshold + lockdown-heat-threshold: 82 # Lockdown heat threshold + + task-bus: + enabled: true + auto-dispatch: true + dispatch-interval-seconds: 10 + queue-limit: 200 + history-limit: 300 + + self-healing: + enabled: true + dry-run: true # Dry-run mode + loop-interval-seconds: 45 + auto-backup-before-recovery: true # Auto-backup before recovery + auto-whitelist-on-swarm: true # Auto-whitelist on bot swarm + allow-soft-restart: true # Allow soft restart + tps-emergency-threshold: 12 # TPS emergency threshold + cpu-emergency-threshold: 92.0 # CPU emergency threshold (%) + memory-emergency-threshold: 95.0 # Memory emergency threshold (%) + max-recovery-actions-per-hour: 8 # Maximum recovery actions per hour ``` -### 3. Data Flow Overview +### SuperEvolution Module Switches (serverguard.security.super-evolution.*) +```yaml + super-evolution: + # === V4.0 Advanced Security Modules === + jwt-auth: true # JWT authentication and token management + brute-force: true # Brute force protection (multi-window detection) + anti-bot: true # Anti-bot detection + reverse-shell: true # Reverse shell detection (50+ pattern matching) + arp-spoof: true # ARP spoofing detection + dns-tunnel: true # DNS tunnel detection (entropy/Base32/suspicious TLDs) + exploit-signature: true # Exploit signature detection (Log4Shell/SQLi/RCE -- 15 types) + ssrf: true # SSRF protection + xxe: true # XXE protection + csp: true # CSP security header enforcement + database-firewall: true # Database firewall + dlp: true # Data loss prevention (12 sensitive info rules) + memory-protection: true # JVM memory protection + process-injection: true # Process injection detection + secure-delete: true # Secure file deletion + forensics: true # Forensic collection + incident-response: true # Incident response (5 predefined playbooks) + threat-hunting: true # Threat hunting (10 hunt definitions) + compliance: true # Compliance scanning (7 categories, 20+ checks) + anti-grief: true # Anti-grief detection + # === Minecraft-Specific Protection === + anti-xray: true # X-ray detection + anti-fly: true # Fly hack detection + anti-dupe: true # Item duplication detection (9 methods) + crash-exploit: true # Crash exploit protection + lag-machine: true # Lag machine detection + # === V4.0 New Modules === + geo-block: true # Geographic IP blocking + session-validation: true # Player session validation + plugin-verification: true # Plugin integrity verification + connection-throttle: true # Connection rate limiting + backup-integrity: true # Backup integrity verification + anti-skin-spoof: true # Skin spoofing detection + # === V4.0 Anti-Cheat Extended === + anti-kill-aura: true # KillAura detection + anti-reach: true # Reach detection + anti-speed: true # Speed detection + anti-jesus: true # Jesus detection + anti-no-fall: true # NoFall detection + anti-scaffold: true # Scaffold detection + anti-timer: true # Timer detection + anti-velocity: true # Velocity detection + anti-phase: true # Phase detection + anti-blink: true # Blink detection + anti-fast-break: true # FastBreak detection + anti-elytra-fly: true # ElytraFly detection + # === V4.0 Player Behavior === + anti-nuker: true # Nuker detection + anti-auto-clicker: true # AutoClicker detection + anti-chest-steal: true # ChestSteal detection + anti-auto-fish: true # AutoFish detection + anti-inventory-manipulation: true # Inventory manipulation detection + anti-baritone: true # Baritone detection + # === V4.0 Server Protection === + packet-flood-protection: true # Packet flood protection + anti-sign-exploit: true # Sign exploit protection + anti-book-ban: true # Book ban protection + anti-resource-pack-exploit: true # Resource pack exploit protection + anti-tab-complete-crash: true # Tab complete crash protection + anti-offline-mode-spoof: true # Offline mode spoof protection + # === V4.0 Access Control === + op-privilege-monitor: true # OP privilege monitoring + config-tamper-detection: true # Config tamper detection + backdoor-plugin-scanner: true # Backdoor plugin scanner + anti-vpn-proxy: true # VPN/proxy detection + anti-alt-account: true # Alt account detection + anti-name-spoof: true # Name spoofing detection + # === V4.0 Chat & Social Security === + chat-flood-protection: true # Chat flood protection + anti-advertisement: true # Advertisement detection + anti-phishing-link: true # Phishing link detection + anti-command-abuse: true # Command abuse detection + player-privacy: true # Player privacy protection + # === V5.0 Server Protection Extended === + chunk-load-rate-limiter: true # Chunk load rate limiter + entity-count-enforcer: true # Entity count enforcer + redstone-update-limiter: true # Redstone update limiter + crash-exploit-signature-db: true # Crash exploit signature database + # === V4.0 Network Protocol Security === + protocol-validator: true # Protocol state validator + token-bucket-rate-limiter: true # Token bucket rate limiter + bot-fingerprint: true # Bot fingerprint detection + nbt-exploit-prevention: true # NBT exploit prevention + handshake-validator: true # Connection handshake validator + # === V5.1 Anti-Cheat Combat (Meteor Client) === + anti-criticals: true # Criticals detection + anti-auto-totem: true # AutoTotem detection + anti-surround: true # Surround detection + anti-auto-trap: true # AutoTrap detection + anti-auto-crystal: true # AutoCrystal detection + anti-auto-armor: true # AutoArmor detection + anti-chest-swap: true # ChestSwap detection + anti-auto-log: true # AutoLog detection + anti-hitboxes: true # Hitboxes detection + anti-bow-aimbot: true # BowAimbot detection + # === V5.2 Anti-Cheat Movement (Meteor Client) === + anti-no-slow: true # NoSlow detection + anti-spider: true # Spider detection + anti-step: true # Step detection + anti-packet-fly: true # PacketFly detection + anti-air-jump: true # AirJump detection + anti-long-jump: true # LongJump detection + anti-anti-hunger: true # AntiHunger detection + anti-fast-fall: true # FastFall detection + anti-vclip: true # VClip detection + # === V5.3 Anti-Cheat World/Player/Misc (Meteor Client) === + anti-speed-mine: true # SpeedMine detection + anti-fast-use: true # FastUse detection + anti-no-interact: true # NoInteract detection + anti-auto-mine: true # AutoMine detection + anti-vein-miner: true # VeinMiner detection + anti-auto-tool: true # AutoTool detection + anti-fake-player: true # FakePlayer detection + anti-piston-aura: true # PistonAura detection + anti-anchor: true # Anchor detection + anti-stash-finder: true # StashFinder detection ``` - ┌──────────────┐ - │ Minecraft │ - │ PaperMC │ - │ (RCON 25575) │ - └──┬───────┬──┘ - │ │ - RCON commands │ │ latest.log - (ban-ip / │ │ /proc metrics - kick / │ │ netstat - whitelist) │ │ - │ │ - ┌────────────────────┴───────┴──────────────────────┐ - │ Aluer ServerGuard │ - │ │ - │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ - │ │ Monitor │ │ Security │ │ AI │ │ - │ │ Process │ │ DDoS/IDS │ │ DeepSeek │ │ - │ │ Resource │ │ WAF/Honey│ │ Anomaly │ │ - │ │ Connect │ │ ZeroTrust│ │ Predict │ │ - │ │ Log │ │ 85+ svc │ │ Adaptive │ │ - │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ - │ │ │ │ │ - │ └─────────┬───┴─────────────┘ │ - │ │ │ - │ ┌────────────┴────────────┐ │ - │ │ Kernel + Sovereign │ │ - │ │ Signal Fusion → Output │ │ - │ └────────────┬────────────┘ │ - │ │ │ - │ ┌────────────┴────────────┐ │ - │ │ AutoExecutor / RCON │ │ - │ │ Execute + Audit Log │ │ - │ └────────────────────────┘ │ - │ │ - │ ┌────────────────────────┐ │ - │ │ Web Dashboard :8080 │ ← Admin Browser │ - │ │ Spring Shell Terminal │ ← Admin Terminal │ - │ └────────────────────────┘ │ - └────────────────────────────────────────────────────┘ - │ - Cloudflare API - (Edge Challenge / Block / Under Attack) + +### Other Configuration Sections + +```yaml + dashboard: + enabled: true + title: "Aluer Nebula Console" + subtitle: "PaperMC defense, recovery, and remote operations fabric" + refresh-interval-seconds: 6 + compact-terminal: true + ssh-gateway: + enabled: true + session-timeout-minutes: 30 + max-sessions: 6 + command-timeout-seconds: 25 + strict-host-key-checking: false + allow-private-key-paste: true + require-engine-handshake: true + handshake-ttl-seconds: 30 + + announcement: + enabled: false + interval-seconds: 300 + messages: + - "Welcome to the server!" + + afk: + enabled: false + afk-timeout-minutes: 5 + max-afk-minutes: 30 + teleport-to-afk-zone: false + afk-zone: "0,100,0" + auto-logout: false + + chat-filter: + enabled: false + block-ip: true + block-profanity: true + block-advertising: true + block-spam: true + block-illegal: true + spam-threshold: 5 + spam-window-seconds: 10 + mute-on-violation: true + mute-duration-minutes: 5 + kick-on-repeat: true + max-violations-before-kick: 3 + + backup: + enabled: false + backup-dir: /opt/minecraft/backups + world-dir: /opt/minecraft/world + plugin-dir: /opt/minecraft/plugins + config-dir: /opt/minecraft + interval-hours: 24 + max-backups: 7 + compress: true + backup-plugins: true + backup-config: false + notify-on-complete: true + + schedule: + enabled: true + daily-restart: true + restart-time: "04:00" + save-before-restart: true + announce-restart: true + announce-message: "Server will restart in {minutes} minutes" + weekly-backup: true + backup-day: sunday + backup-time: "03:00" + clear-lag-daily: true + clear-lag-time: "02:00" ``` --- -## 🚀 Quick Start +## WebSocket Communication Protocol + +### Message Format + +All messages are single-line JSON transmitted via WebSocket text frames. + +**Agent to Server event message:** + +```json +{ + "type": "EVENT", + "agentId": "agent-survival-01", + "timestamp": 1715000000000, + "payload": { + "eventType": "PLAYER_MOVE", + "playerName": "Steve", + "x": 100.5, + "y": 64.0, + "z": 200.3, + "yaw": 45.0, + "pitch": 0.0 + } +} +``` + +**Agent to Server heartbeat:** + +```json +{ + "type": "HEARTBEAT", + "agentId": "agent-survival-01", + "timestamp": 1715000005000, + "payload": { + "status": "alive" + } +} +``` + +**Server to Agent command:** + +```json +{ + "type": "COMMAND", + "requestId": "550e8400-e29b-41d4-a716-446655440000", + "timestamp": 1715000001000, + "payload": { + "command": "KICK", + "target": "Hacker123", + "reason": "KillAura detected - confidence 94%" + } +} +``` + +### Complete Event Types + +| Event Constant | Value | Description | +|---------------|-------|-------------| +| EVENT_PLAYER_JOIN | PLAYER_JOIN | Player joined server | +| EVENT_PLAYER_QUIT | PLAYER_QUIT | Player left server | +| EVENT_PLAYER_MOVE | PLAYER_MOVE | Player moved (x/y/z coordinates, yaw/pitch angles) | +| EVENT_PLAYER_TELEPORT | PLAYER_TELEPORT | Player teleported | +| EVENT_PLAYER_CHAT | PLAYER_CHAT | Chat message | +| EVENT_PLAYER_COMMAND | PLAYER_COMMAND | Command executed | +| EVENT_PLAYER_DAMAGE | PLAYER_DAMAGE | Player took damage | +| EVENT_COMBAT_ATTACK | COMBAT_ATTACK | Attack event (attacker/target/damage) | +| EVENT_COMBAT_DEATH | COMBAT_DEATH | Death event | +| EVENT_BLOCK_BREAK | BLOCK_BREAK | Block broken (block type/coordinates/tool) | +| EVENT_BLOCK_PLACE | BLOCK_PLACE | Block placed | +| EVENT_INVENTORY_CLICK | INVENTORY_CLICK | Inventory interaction (slot/item type) | +| EVENT_ENTITY_SPAWN | ENTITY_SPAWN | Entity spawned | +| EVENT_CHUNK_LOAD | CHUNK_LOAD | Chunk loaded | + +### Complete Command Types + +| Command Constant | Value | Description | +|-----------------|-------|-------------| +| CMD_BAN_IP | BAN_IP | Ban IP address | +| CMD_BAN_PLAYER | BAN_PLAYER | Ban player account | +| CMD_KICK | KICK | Kick player from server | +| CMD_CLEAR_LAG | CLEAR_LAG | Remove all non-player entities | +| CMD_SET_SPAWN_RATE | SET_SPAWN_RATE | Dynamically adjust mob spawn rate | +| CMD_ENABLE_WHITELIST | ENABLE_WHITELIST | Enable server whitelist | +| CMD_DISABLE_WHITELIST | DISABLE_WHITELIST | Disable server whitelist | +| CMD_BROADCAST | BROADCAST | Broadcast message to all players | +| CMD_SAVE_ALL | SAVE_ALL | Force save all worlds | +| CMD_EXECUTE | EXECUTE | Execute arbitrary console command | + +--- + +## Alert Types + +The system supports 75 alert types defined in `AlertType.java`: + +**System Monitoring (8):** +PROCESS_DEAD, TPS_LOW, CPU_HIGH, MEM_HIGH, CONNECTION_FLOOD, LOG_ATTACK, BACKUP_FAILED, AI_ANOMALY + +**V4.0 Anti-Cheat (10):** +SECURITY_KILL_AURA, SECURITY_REACH, SECURITY_SPEED, SECURITY_JESUS, SECURITY_NOFALL, SECURITY_SCAFFOLD, SECURITY_NUKER, SECURITY_AUTO_CLICKER, SECURITY_AUTO_FISH, SECURITY_FLY + +**V5.0 Anti-Cheat (6):** +SECURITY_TIMER, SECURITY_VELOCITY, SECURITY_PHASE, SECURITY_BLINK, SECURITY_FAST_BREAK, SECURITY_ELYTRA_FLY + +**V5.1 Combat (10):** +SECURITY_CRITICALS, SECURITY_AUTO_TOTEM, SECURITY_SURROUND, SECURITY_AUTO_TRAP, SECURITY_AUTO_CRYSTAL, SECURITY_AUTO_ARMOR, SECURITY_CHEST_SWAP, SECURITY_AUTO_LOG, SECURITY_HITBOXES, SECURITY_BOW_AIMBOT + +**V5.2 Movement (9):** +SECURITY_NO_SLOW, SECURITY_SPIDER, SECURITY_STEP, SECURITY_PACKET_FLY, SECURITY_AIR_JUMP, SECURITY_LONG_JUMP, SECURITY_ANTI_HUNGER, SECURITY_FAST_FALL, SECURITY_VCLIP + +**V5.3 World/Misc (10):** +SECURITY_SPEED_MINE, SECURITY_FAST_USE, SECURITY_NO_INTERACT, SECURITY_AUTO_MINE, SECURITY_VEIN_MINER, SECURITY_AUTO_TOOL, SECURITY_FAKE_PLAYER, SECURITY_PISTON_AURA, SECURITY_ANCHOR, SECURITY_STASH_FINDER + +**Player Behavior (6):** +SECURITY_CHEST_STEAL, SECURITY_INVENTORY_MANIPULATION, SECURITY_GRIEF, SECURITY_ALT_ACCOUNT, SECURITY_BARITONE, SECURITY_XRAY + +**Server Protection (9):** +SECURITY_SIGN_EXPLOIT, SECURITY_BOOK_BAN, SECURITY_RESOURCE_PACK_EXPLOIT, SECURITY_TAB_COMPLETE_CRASH, SECURITY_OFFLINE_MODE_SPOOF, SECURITY_CHUNK_RATE, SECURITY_ENTITY_LIMIT, SECURITY_REDSTONE_LAG, SECURITY_CRASH_EXPLOIT + +**Chat Security (4):** +CHAT_FLOOD, CHAT_ADVERTISEMENT, CHAT_PHISHING, COMMAND_ABUSE + +**Network Security (9):** +SECURITY_DDOS, SECURITY_PORT_SCAN, SECURITY_BRUTE_FORCE, SECURITY_VPN_PROXY, SECURITY_DNS_TUNNEL, SECURITY_PROTOCOL_VIOLATION, SECURITY_BOT_FINGERPRINT, SECURITY_NBT_EXPLOIT, SECURITY_HANDSHAKE_ANOMALY + +**Host Security (5):** +SECURITY_REVERSE_SHELL, SECURITY_PROCESS_INJECTION, SECURITY_FILE_TAMPER, SECURITY_BACKDOOR_PLUGIN, SECURITY_CONFIG_TAMPER + +**ML Analysis (4):** +ML_BEHAVIOR_ANOMALY, ML_THREAT_ESCALATION, ML_MOVEMENT_PATTERN, ML_COMBAT_PATTERN + +**General (1):** +SECURITY_OTHER + +--- + +## Testing Guide + +### Run Full Test Suite + +```bash +cd /opt/AluerIII +./apache-maven-3.9.6/bin/mvn test +``` + +### Testing Conventions + +This project follows strict testing discipline: +- **Live Fire Testing**: Tests must simulate real Minecraft server environments +- **Production Alignment**: Test data and behavior must match actual production environments +- **Dual Constructor Pattern**: Each Service class provides both a no-arg constructor (for testing) and an @Autowired constructor (for production injection) +- **Static Factory Methods**: Detection results use `clean()`, `blocked()`, `flagged()` static factory methods +- **Full Suite Validation**: Full test suite must pass before and after every code change + +### Build Commands + +```bash +# Compile +./apache-maven-3.9.6/bin/mvn compile + +# Run full test suite +./apache-maven-3.9.6/bin/mvn test + +# Package (skip tests for quick deployment) +./apache-maven-3.9.6/bin/mvn package -DskipTests + +# Clean build artifacts +./apache-maven-3.9.6/bin/mvn clean +``` + +--- + +## Project Structure + +``` +AluerIII/ +├── pom.xml # Maven build configuration +├── application.yml # Spring Boot configuration (316 lines) +├── CLAUDE.md # Development guidelines +├── README.md # Project README (Chinese) +├── README_EN.md # Project README (English) +├── docs/ +│ ├── DEVELOPER.md # Developer reference +│ ├── PROJECT_SUMMARY.md # Project overview and module breakdown +│ └── USER_MANUAL.md # User manual +├── apache-maven-3.9.6/ # Bundled Maven 3.9.6 +├── src/ +│ ├── main/java/com/aluer/ +│ │ ├── ServerGuardApplication.java # Spring Boot entry point +│ │ ├── config/ +│ │ │ └── ServerGuardConfig.java # Full configuration class (1273 lines, includes SuperEvolutionConfig) +│ │ ├── model/ +│ │ │ └── AlertType.java # Alert type enum (75 alert types) +│ │ ├── agent/ +│ │ │ └── AgentMessage.java # Agent communication protocol +│ │ ├── security/ # Security modules (123 Java files) +│ │ │ ├── AntiKillAuraService.java +│ │ │ ├── AntiReachService.java +│ │ │ ├── AntiAutoCrystalService.java +│ │ │ ├── ... (120+ more) +│ │ │ └── ZeroTrustArchitectureService.java +│ │ ├── ml/ # ML modules (4 files) +│ │ │ ├── BehavioralProfilingEngine.java +│ │ │ ├── CombatPatternRecognizer.java +│ │ │ ├── MovementPatternAnalyzer.java +│ │ │ └── ThreatScoreAggregator.java +│ │ ├── plugin/ # Paper plugin implementation +│ │ │ ├── AluerPlugin.java # Plugin main class (JavaPlugin) +│ │ │ ├── AluerCommandExecutor.java # Command registrar +│ │ │ ├── bridge/ +│ │ │ │ ├── AgentWebSocketClient.java # WebSocket client +│ │ │ │ ├── DataBridge.java # Data format bridge +│ │ │ │ └── InternalCommandExecutor.java # Bukkit API command executor +│ │ │ └── listener/ # Bukkit event listeners (9) +│ │ │ ├── BlockEventListener.java # Block events (break/place) +│ │ │ ├── ChatEventListener.java # Chat/social events +│ │ │ ├── CombatEventListener.java # Combat events (attack/death) +│ │ │ ├── CommandEventListener.java # Command execution events +│ │ │ ├── EntityEventListener.java # Entity spawn/despawn events +│ │ │ ├── InventoryEventListener.java # Inventory/container events +│ │ │ ├── PacketEventListener.java # Raw packet events +│ │ │ ├── PlayerEventListener.java # Player join/quit/move events +│ │ │ └── WorldEventListener.java # World/chunk events +│ │ ├── controller/ +│ │ │ └── TestController.java # Test controller +│ │ └── websocket/ # WebSocket server +│ └── main/resources/ +│ └── application.yml # Default configuration file +└── src/test/ # Test code directory +``` + +--- + +## Development Guide + +### Quick Start + +```bash +# 1. Clone repository +git clone +cd AluerIII + +# 2. Compile +./apache-maven-3.9.6/bin/mvn compile + +# 3. Run tests +./apache-maven-3.9.6/bin/mvn test + +# 4. Package +./apache-maven-3.9.6/bin/mvn package -DskipTests +``` ### Requirements | Dependency | Version | Notes | |------------|---------|-------| -| JDK | 17+ | Compile and runtime | -| Maven | 3.9+ (bundled) | `apache-maven-3.9.6/` included in repo | -| OS | Ubuntu / Debian | Recommended for production; other Linux works but some security modules need iptables/ufw | -| Memory | 2 GB+ free | On top of Minecraft server's own memory | -| Disk | 10 GB+ | Logs + backups + jar | -| Minecraft | PaperMC 1.21+ | RCON must be enabled (`enable-rcon=true` in `server.properties`) | -| DeepSeek | API Key | Required for AI decision and natural language Q&A | -| Node.js | 18+ (dev only) | Production uses pre-built static assets | +| Java JDK | 21+ | Compilation and runtime | +| Maven | 3.9.6 | Bundled with project | +| PaperMC | 1.21.1 | Minecraft server (Plugin mode only) | -### Build +### Development Conventions -```bash -# 1. Clone the repository -git clone https://github.com/ZpjDev/Aluer.git -cd Aluer - -# 2. Build with bundled Maven -./apache-maven-3.9.6/bin/mvn clean package -DskipTests - -# 3. Output location -ls -lh target/serverguard.jar -``` - -The build process also compiles the React frontend via Vite, outputting to `src/main/resources/static/` and embedding into the jar. - -### Environment Variables - -**Minimum viable config** (only 2 env vars required): - -```bash -# Required: DeepSeek API Key (get from https://platform.deepseek.com) -export DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - -# Required: RCON password (must match rcon.password in server.properties) -export RCON_PASSWORD=your-strong-rcon-password -``` - -**Full production config**: - -```bash -# ──── Core Credentials ──── -export DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -export DEEPSEEK_BASE_URL=https://api.deepseek.com -export DEEPSEEK_MODEL=deepseek-chat -export RCON_PASSWORD=your-strong-rcon-password - -# ──── Email Alerts (QQ email example) ──── -export ALUER_ALERT_SMTP_USERNAME=your-email@qq.com -export ALUER_ALERT_SMTP_PASSWORD=your-smtp-auth-code -export ALUER_ALERT_EMAIL_PRIMARY=admin@example.com -export ALUER_ALERT_EMAIL_SECONDARY=backup@example.com - -# ──── Cloudflare Edge Protection (optional) ──── -export ALUER_CLOUDFLARE_ZONE_ID=your-zone-id -export ALUER_CLOUDFLARE_API_KEY=your-api-key -export ALUER_CLOUDFLARE_EMAIL=your-cloudflare-email - -# ──── Discord/Slack Webhooks (optional) ──── -export ALUER_WEBHOOK_DISCORD=https://discord.com/api/webhooks/xxx/yyy -export ALUER_WEBHOOK_SLACK=https://hooks.slack.com/services/xxx/yyy/zzz -``` - -> **Security note**: Never hardcode API keys or passwords in `application.yml`. All sensitive values use `${VAR_NAME:}` placeholder syntax, defaulting to empty string when not set. - -### First Launch - -```bash -# Foreground (shows Spring Shell interactive terminal) -java -jar target/serverguard.jar - -# Background (using provided script) -./start.sh - -# Using systemd (recommended for production) -sudo systemctl start serverguard -``` - -On startup you'll see the Spring Shell terminal: - -``` -╔══════════════════════════════════════════════════╗ -║ Welcome to Aluer ServerGuard ║ -╠══════════════════════════════════════════════════╣ -║ Type help for available commands ║ -║ Type ai for AI assistant ║ -╚══════════════════════════════════════════════════╝ -aluer> -``` - -Verify everything is working: - -```bash -# Test API -curl http://localhost:8080/api/status - -# Expected response -{"status":"running","timestamp":1746883200000} - -# Access Web Console -curl http://localhost:8080/ -``` - -### One-Click Install - -```bash -# Run with sudo -sudo bash install.sh -``` - -The script will: -1. Detect/install Java 17 -2. Create `/opt/serverguard/` working directory -3. Wait for you to upload the jar (via `scp` or other) -4. Auto-create and enable systemd service -5. Start service and verify status +See `CLAUDE.md` in the project root. Core principles: +- **YOLO Mode**: Execute directly, do not wait for confirmation +- **Chinese Comments**: Detailed Chinese comments on every method and critical logic, explain WHY not WHAT +- **Testing Discipline**: Full test suite before and after every code change +- **Frequent Commits**: Each meaningful change gets its own Git commit with Chinese commit messages +- **Zero Pseudocode**: Every line of code must be compilable, runnable, and verifiable --- -## 📦 Deployment Guide +## Performance Characteristics -### Systemd Services - -The repo provides two systemd unit files: - -**`systemd/minecraft.service`** — Minecraft server (Aluer's prerequisite): - -```ini -[Unit] -Description=Minecraft PaperMC Server -After=network.target - -[Service] -Type=simple -User=minecraft -WorkingDirectory=/opt/minecraft -ExecStart=/usr/bin/java -Xms4G -Xmx4G -jar paper-1.21.11.jar nogui -Restart=on-failure -RestartSec=10 -StartLimitBurst=3 - -[Install] -WantedBy=multi-user.target -``` - -**`systemd/serverguard.service`** — Aluer protection system: - -```ini -[Unit] -Description=Aluer ServerGuard Protection System -After=network.target minecraft.service -Requires=minecraft.service - -[Service] -Type=simple -User=root -WorkingDirectory=/opt/serverguard -ExecStart=/usr/bin/java -jar serverguard.jar -Restart=always -RestartSec=5 - -[Install] -WantedBy=multi-user.target -``` - -Deployment steps: - -```bash -# 1. Copy service files -sudo cp systemd/minecraft.service /etc/systemd/system/ -sudo cp systemd/serverguard.service /etc/systemd/system/ - -# 2. Create minecraft user -sudo useradd -r -m -d /opt/minecraft minecraft - -# 3. Reload systemd -sudo systemctl daemon-reload - -# 4. Start Minecraft first, then Aluer -sudo systemctl enable --now minecraft -sudo systemctl enable --now serverguard - -# 5. Check status -sudo systemctl status minecraft serverguard - -# 6. Watch Aluer logs -sudo journalctl -u serverguard -f -``` - -### sudo Configuration - -Aluer needs permission to run `systemctl restart minecraft`. Copy the sudoers file: - -```bash -sudo cp systemd/sudoers.serverguard /etc/sudoers.d/serverguard -sudo chmod 440 /etc/sudoers.d/serverguard -``` - -### Reverse Proxy (Optional) - -When exposing the web console publicly, place Nginx in front: - -```nginx -server { - listen 443 ssl; - server_name console.your-server.com; - - auth_basic "Aluer Console"; - auth_basic_user_file /etc/nginx/.htpasswd; - - location / { - proxy_pass http://127.0.0.1:8080; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - } -} -``` - -> **Warning**: Never expose Aluer's port 8080 directly to the internet. The WAF module provides basic protection only and is not a substitute for a proper reverse proxy. +| Metric | Plugin Mode | External Mode | +|--------|------------|---------------| +| Communication Latency | < 1ms (same-machine WebSocket) | Depends on RCON response | +| Event Throughput | 50,000+ events/sec | 10,000+ events/sec | +| Online Player Capacity | 100+ (single agent) | 100+ | +| Memory Footprint | ~50MB (plugin portion) | ~200MB (full engine) | +| Module Hot-Switching | Supported | Supported | +| Automatic Recovery | Fully automatic (self-healing) | Fully automatic | +| DDoS Defense | Multi-layer coordinated | Multi-layer coordinated | +| AI Decision Latency | ~45s (DeepSeek analysis) | ~45s | +| Use Case | Production servers (recommended) | Monitoring/backup scenarios | --- -## ⚙️ Configuration Reference +## License -### Full Config Tree - -All top-level configuration nodes in `application.yml` and their purposes: - -``` -serverguard -├── minecraft # Minecraft server connection -│ ├── service-name # systemd service name (default: minecraft) -│ ├── process-name # Process name for liveness detection -│ ├── jar-file # PaperMC jar filename -│ ├── working-dir # Minecraft working directory -│ ├── java-opts # JVM startup args -│ ├── check-interval-seconds # Monitor check interval (default: 5s) -│ └── rcon -│ ├── enabled -│ ├── host # RCON host (default: localhost) -│ ├── port # RCON port (default: 25575) -│ └── password # RCON password (${RCON_PASSWORD}) -│ -├── monitor # Monitoring thresholds -│ ├── tps-threshold # TPS alert threshold (default: 15) -│ ├── cpu-threshold # CPU usage alert % (default: 80) -│ ├── memory-threshold # Memory usage alert % (default: 85) -│ ├── connection-threshold # Connection anomaly threshold -│ ├── log-watch-lines # Log tail lines -│ └── log-path # Minecraft log file path -│ -├── alert # Alert notification config -│ ├── enabled -│ └── email -│ ├── smtp-host -│ ├── smtp-port # (default: 587) -│ ├── username # (${ALUER_ALERT_SMTP_USERNAME}) -│ ├── password # (${ALUER_ALERT_SMTP_PASSWORD}) -│ ├── to # Recipient list (env var injected) -│ └── rate-limit -│ ├── per-type-seconds # Cooldown per alert type (default: 300s) -│ └── max-emails-per-minute -│ -├── ai # AI engine config -│ ├── enabled -│ ├── use-isolation-forest -│ ├── use-prediction -│ ├── sliding-window-size -│ ├── anomaly-threshold # (0-1) -│ ├── prediction-horizon-minutes -│ └── deepseek -│ ├── enabled -│ ├── api-key # (${DEEPSEEK_API_KEY}) -│ ├── base-url # (default: https://api.deepseek.com) -│ ├── model # (default: deepseek-chat) -│ ├── max-tokens -│ ├── temperature # (0-1, recommended 0.35) -│ ├── auto-analyze-alerts -│ ├── analysis-interval-seconds -│ └── auto-execute -│ ├── enabled -│ ├── ban-ip / kill-entity / clear-lag -│ ├── set-spawn-rate / kick-player / whitelist -│ └── min-confidence # (default: 88) -│ -├── security # Security module config -│ ├── enabled # Master switch -│ ├── auto-ban-vpn -│ ├── check-on-login -│ ├── max-connections-per-ip -│ ├── block-common-exploits -│ ├── log-all-commands -│ │ -│ ├── minecraft-defense # Minecraft protocol defense -│ ├── ddos-defense # DDoS multi-layer detection -│ ├── anti-intrusion # Intrusion detection config -│ ├── host-enforcement # Host firewall enforcement -│ ├── cloud-edge # Cloudflare edge protection -│ ├── orchestration # Orchestration policies -│ ├── autonomy # Autonomous defense policies -│ ├── shield # Mirage Shield config -│ ├── kernel # Kernel engine config -│ ├── task-bus # Task bus config -│ └── self-healing # Self-healing orchestration -│ -├── webhook # Discord/Slack notifications -│ ├── enabled -│ ├── discord-url # (${ALUER_WEBHOOK_DISCORD}) -│ └── slack-url # (${ALUER_WEBHOOK_SLACK}) -│ -├── dashboard # Web console config -├── backup # Backup config -├── schedule # Scheduled tasks -├── chat-filter # Chat filtering -├── announcement # Timed announcements -└── afk # AFK management -``` - -### Environment Variable Injection Table - -| Env Variable | Config Path | Default | -|-------------|-------------|---------| -| `RCON_PASSWORD` | `serverguard.minecraft.rcon.password` | (empty) | -| `DEEPSEEK_API_KEY` | `serverguard.ai.deepseek.api-key` | (empty) | -| `DEEPSEEK_BASE_URL` | `serverguard.ai.deepseek.base-url` | `https://api.deepseek.com` | -| `DEEPSEEK_MODEL` | `serverguard.ai.deepseek.model` | `deepseek-chat` | -| `ALUER_ALERT_SMTP_USERNAME` | `serverguard.alert.email.username` | (empty) | -| `ALUER_ALERT_SMTP_PASSWORD` | `serverguard.alert.email.password` | (empty) | -| `ALUER_ALERT_EMAIL_PRIMARY` | `serverguard.alert.email.to[0]` | (empty) | -| `ALUER_ALERT_EMAIL_SECONDARY` | `serverguard.alert.email.to[1]` | (empty) | -| `ALUER_CLOUDFLARE_ZONE_ID` | `serverguard.security.cloud-edge.zone-id` | (empty) | -| `ALUER_CLOUDFLARE_API_KEY` | `serverguard.security.cloud-edge.api-key` | (empty) | -| `ALUER_CLOUDFLARE_EMAIL` | `serverguard.security.cloud-edge.api-email` | (empty) | -| `ALUER_WEBHOOK_DISCORD` | `serverguard.webhook.discord-url` | (empty) | -| `ALUER_WEBHOOK_SLACK` | `serverguard.webhook.slack-url` | (empty) | - ---- - -## 📋 Module Catalog - -### AI Decision Layer (`com.aluer.ai`) - -| Class | File | Description | -|-------|------|-------------| -| `AluerSovereignEngine` | `ai/AluerSovereignEngine.java` | **L1 Sovereign Engine**. Collects network posture → DeepSeek generates `AutonomyDirective` (workflow + defenseLevel + riskScore). Built-in workflow whitelist prevents LLM hallucination. | -| `DeepSeekClient` | `ai/DeepSeekClient.java` | **DeepSeek API Client**. Native `HttpURLConnection`. Supports 4 call modes: alert analysis, health report, free-form Q&A, and autonomous defense planning. Built-in JSON extraction from markdown/text. | -| `AIAutonomousService` | `ai/AIAutonomousService.java` | **L3 Execution Layer**. Reads L1 + L2 directives, conflict arbitration, cooldown, rate limiting, dual-signal confirmation. Translates decisions into RCON commands. | -| `AIStrategyEngine` | `ai/AIStrategyEngine.java` | **Strategy Matching Engine**. Maps threat types to optimal defense strategies (brute force → temp ban+captcha, DDoS → traffic scrubbing+rate limit). | -| `AnomalyDetector` | `ai/AnomalyDetector.java` | **Isolation Forest**. Based on Apache Commons Math3. Unsupervised anomaly detection on CPU/memory/TPS/connections. | -| `TimeSeriesPredictor` | `ai/TimeSeriesPredictor.java` | **Time Series Predictor**. Sliding window historical data → predict TPS trends 60min ahead. | -| `AdaptiveThreshold` | `ai/AdaptiveThreshold.java` | **Adaptive Thresholds**. Learns server load patterns, dynamically adjusts alert thresholds to reduce false positives during low-load hours. | - -### Kernel Engine Layer (`com.aluer.kernel`) - -| Class | File | Description | -|-------|------|-------------| -| `AluerKernelEngine` | `kernel/AluerKernelEngine.java` | **L2 Kernel Engine**. 30s Pulse loop. 5 virtual modules (ThreatMesh / CommandLattice / HardeningMatrix / PerimeterWard / EchoGrid), weighted signal fusion, heat/resonance/control 3D pressure, adaptive weights, EchoGrid attacker memory decay. | -| `AluerKernelTaskBus` | `kernel/AluerKernelTaskBus.java` | **Task Bus**. Plugin-based task execution framework. 4 built-in Plugins (Insight / Stability / Defense / Recovery) dispatched by priority. | -| `AluerSelfHealingOrchestrator` | `kernel/AluerSelfHealingOrchestrator.java` | **Self-Healing Orchestrator**. 45s recovery check. Detects TPS/CPU/memory emergency thresholds. Recovery actions: soft restart, clear entities, adjust spawn rate, whitelist (bot swarm). Max 8 recovery actions/hour. | - -### Security Defense Layer (`com.aluer.security`) - -The largest package in the system, containing 85+ security services (with 31 advanced extended security modules, V4.0 complete edition): - -| Category | Key Classes | Description | -|----------|------------|-------------| -| **DDoS Defense** | `DDoSProtectionService`, `DDoSDefenseCoordinator`, `DistributedAttackMitigationService`, `MinecraftProtocolSecurityService` | SYN/HTTP/UDP/ICMP Flood detection, Minecraft-specific Status/Login/Rcon/Query Flood | -| **Firewall** | `FirewallService`, `HostEnforcementService`, `NetworkMonitorService`, `NetworkSegmentationService` | iptables/ufw rule management, auto/iptables/ufw/nftables backend support | -| **Intrusion Detection** | `IntrusionDetectionService`, `IntrusionPreventionSystem`, `HostIntrusionCountermeasureService`, `LogAnalysisService`, `LogCorrelationService` | Signature-based IDS, auto-blocking, multi-source log correlation | -| **Application Security** | `WebApplicationFirewall`, `WafRequestFilter`, `APIRateLimitService`, `RateLimitService` | SQLi/XSS/path traversal/header injection protection, client reputation scoring | -| **Advanced Defense** | `HoneypotService`, `ZeroTrustArchitectureService`, `AdvancedMalwareDetectionService`, `EndpointDetectionResponseService`, `ContainerSecurityService` | Honeypot decoys, continuous auth verification, malware scanning, EDR | -| **Network Analysis** | `TrafficAnalysisService`, `PacketInspectionService`, `FlowAnalyzerService`, `PortScanDetectionService`, `ProtocolAnalysisService` | Traffic pattern analysis, DPI, NetFlow/sFlow, port scan detection | -| **IP Intelligence** | `IPReputationService`, `GeoIPService`, `ThreatIntelligenceService`, `VPNDetectionService` | IP reputation scoring, geolocation filtering, threat feed integration, VPN/proxy detection | -| **SSL/TLS** | `SSLMonitorService`, `SSLTLSCertificateService` | Certificate expiry monitoring, cert management | -| **Security Operations** | `SIEMService`, `SecurityOrchestrationService`, `SecurityAutomationScheduler`, `SecurityBaselineHardeningService`, `BackupSecurityService` | SIEM correlation, security orchestration, baseline hardening | -| **Command Security** | `CommandExecutionGuardService` | Dangerous command interception (rm -rf / wget \| sh / privilege escalation) | -| **Execution Layer** | `CloudflareIntegrationService`, `DNSSecurityService`, `SessionManagementService`, `LoadBalancerService`, `TrafficShapingService`, `EncryptionService` | Cloudflare API integration, DNS security, session management, load balancing, traffic shaping | -| **Advanced Extensions** | `JwtAuthService` | JWT HMAC-SHA256 auth with constant-time comparison | -| | `BruteForceProtectionService` | Three-layer time window (60s/600s/3600s) brute force defense | -| | `AntiBotDetectionService` | Minecraft bot detection: name patterns/join velocity/multi-account | -| | `AntiGriefDetectionService` | Block break/place rate monitoring, dangerous block detection | -| | `ReverseShellDetectionService` | 50+ reverse shell pattern matching + obfuscated command detection | -| | `ARPSpoofDetectionService` | ARP table baseline diff, MAC/Gateway spoof detection | -| | `DNSTunnelDetectionService` | Subdomain entropy analysis, Base64 encoding detection | -| | `ExploitSignatureService` | 15+ exploit signatures (Log4Shell/SQLi/XSS/Deserialization) | -| | `SSRFProtectionService` | Internal IP/Cloud metadata/DNS rebinding protection | -| | `XXEProtectionService` | XML entity injection + Billion Laughs attack detection | -| | `CSPEnforcementService` | Content-Security-Policy + 8 security headers auto-generation | -| | `DatabaseFirewallService` | SQL injection detection (UNION/sleep/stacked queries) | -| | `DataLossPreventionService` | 12 sensitive data patterns (email/API key/SSH key/JWT/card) | -| | `MemoryProtectionService` | JVM heap/GC overload/memory leak pattern detection | -| | `ProcessInjectionDetectionService` | Thread spike/memory mapping/non-standard native lib detection | -| | `SecureFileDeletionService` | DoD multi-pass overwrite (0x00/random/0xFF/0xAA) secure delete | -| | `ForensicsCollectorService` | 6 evidence types (process/network/files/logs) case management | -| | `IncidentResponseService` | 5 playbooks (DDoS/brute force/intrusion/MC exploit/data breach) | -| | `ThreatHuntingService` | 10 proactive hunt rules (persistence/lateral/privilege/crypto/webshell) | -| | `ComplianceScannerService` | 7 categories 20+ checks, auto compliance scoring (0-100%) | -| **Minecraft-Specific** | `AntiXrayDetectionService` | X-ray detection: diamond/stone ratio, straight-line mining, dark precision | -| | `AntiFlyDetectionService` | Fly/speed/teleport hack detection: vertical/horizontal limits, air time | -| | `AntiDupeDetectionService` | Item duplication detection: stack overflow, high-value item surges, 9 known methods | -| | `CrashExploitProtectionService` | Crash exploit protection: oversized packets, NBT bombs, book/sign exploits | -| | `LagMachineDetectionService` | Lag machine detection: observer chains, TNT stacks, entity spam, falling blocks | -| **V4.0 Extensions** | `GeoBlockService` | Geo IP blocking: country allowlist/blocklist, high-risk Minecraft attack source interception | -| | `PlayerSessionValidationService` | Player session validation: UUID format, offline/premium detection, session replay, multi-account | -| | `PluginVerificationService` | Plugin integrity verification: SHA-256 hash comparison, malicious plugin name detection | -| | `ConnectionThrottleService` | Connection rate limiting: multi-window IP tracking, progressive delay (2s/5s/15s/30s) | -| | `BackupIntegrityService` | Backup integrity verification: SHA-256 checksum, file existence/size comparison, 6h auto-scan | -| | `AntiSkinSpoofService` | Skin spoofing detection: impersonation detection, suspicious URL checks, skin change frequency | - -### Operations Control Layer (`com.aluer.console`) - -| Class | Description | -|-------|-------------| -| `AluerOperationsCenterService` | **Operations Center**. Aggregates all subsystem status, outputs to `/api/console/overview` | -| `AluerMirageShieldService` | **Mirage Shield**. 4-mode adaptive protection (OBSERVE → FORTIFY → MIRAGE → SHELTER), attacker deterrence, auto mode switching | -| `RemoteSshGatewayService` | **Remote SSH Gateway**. Built-in terminal, Sovereign Handshake approval + command guard integration | -| `ConsoleStreamController` | **SSE Stream**. Server-Sent Events push of real-time overview data to frontend | - -### Monitoring Collection Layer (`com.aluer.monitor`) - -| Class | Description | -|-------|-------------| -| `ProcessMonitor` | Process liveness detection, auto-restart Minecraft on crash | -| `ResourceMonitor` | System resource collection (CPU/memory/disk I/O) via `/proc` and JMX | -| `ConnectionMonitor` | Network connection statistics, Connection Flood detection | -| `LogMonitor` | Minecraft `latest.log` real-time tracking, crash stack and anomaly detection | - -### Core Service Layer (`com.aluer.service`) - -| Class | Description | -|-------|-------------| -| `ServerGuardService` | **System Controller**. `CommandLineRunner` entry point, schedules all monitoring and AI analysis loops | -| `RconClient` | Minecraft RCON protocol client, native NIO SocketChannel implementation with fallback | -| `AutoExecutor` | Translates AI decisions into RCON commands (e.g., "ban IP" → `/ban-ip 1.2.3.4`) | - -### Web Interaction Layer (`com.aluer.web`) - -| Class | Description | -|-------|-------------| -| `DashboardController` | REST API (`/api/*`): status, commands, backups, health checks, attack reports | -| `OperationsConsoleController` | Console API (`/api/console/*`): overview, shield control, quick actions | -| `ConsoleStreamController` | SSE stream (`/api/console/stream/overview`) | -| `HealthService` | Component-level health checks (RCON/AI/email/security/self-healing), system resources | -| `RequestLoggingFilter` | HTTP request logging, slow request and 500 error alerts | - -### Notification & Reporting Layer (`com.aluer.notification`) - -| Class | Description | -|-------|-------------| -| `WebhookService` | Discord/Slack dual-channel webhook push. Auto-sends embed messages on security alerts with color-coded severity | -| `AttackReportService` | Records last 500 attack events in memory ring buffer. Generates timestamped HTML security reports | - -### Auxiliary Modules - -| Package | Class | Description | -|---------|-------|-------------| -| `com.aluer.alert` | `EmailAlertService` | Email alerts with QQ/Gmail/custom SMTP, built-in rate limiting | -| `com.aluer.backup` | `BackupService` | World/plugin/config scheduled backup, compression, auto-cleanup | -| `com.aluer.anticheat` | `AntiCheatService` | Anti-cheat integration, aggregated violation data | -| `com.aluer.vpn` | `VPNDetectionService` | VPN/proxy IP detection | -| `com.aluer.chat` | `ChatFilterService` | In-game chat filtering (profanity/ads/phishing/spam) | -| `com.aluer.punishment` | `PunishmentService` | Unified punishment management (ban/kick/mute) | -| `com.aluer.audit` | `SecurityAuditService` | Security audit logs for all admin operations | -| `com.aluer.world` | `WorldManagementService` | Minecraft world management (load/unload/list) | -| `com.aluer.metrics` | `MetricsCollectionService` | Unified metrics aggregation | -| `com.aluer.profiler` | `PerformanceProfiler` | CPU/memory/tick performance analyzer | -| `com.aluer.schedule` | `ScheduledTaskService` | Task scheduling engine (restart/backup/clear lag/announce) | -| `com.aluer.export` | `DataExportService` | Security data export (audit/attack/performance reports) | -| `com.aluer.command` | `AdminCommands` / `TestCommands` | Spring Shell management and test commands | - -### Data Models (`com.aluer.model`) - -| Class | Fields | Description | -|-------|--------|-------------| -| `AlertEvent` | type, message, rootCause, timestamp, confidence, suggestedAction | Standardized alert event | -| `AlertType` | PROCESS_DEAD / TPS_LOW / CPU_HIGH / MEM_HIGH / CONNECTION_FLOOD / LOG_ATTACK / BACKUP_FAILED / AI_ANOMALY | Alert type enum | -| `MetricsData` | tps, cpuUsage, memoryUsage, onlinePlayers, connections, tickTime | Server performance snapshot | - ---- - -## 🛡️ Defense Levels & Auto Response - -### Four-Tier Defense System - -The system auto-switches defense levels based on Kernel heat and Sovereign assessment: - -| Level | Heat Range | Trigger | Auto Actions | -|-------|-----------|---------|--------------| -| `NORMAL` | < 45 | Normal operation | Routine monitoring, anomalies logged only | -| `ELEVATED` | 45–69 | Single module pressure rise | Increased detection frequency, IP reputation queries enabled | -| `HIGH` | 70–81 | Multiple modules alerting | Auto-block high-risk IPs, rate limiting, edge challenges | -| `LOCKDOWN` | ≥ 82 | Severe compound attack | Whitelist mode, Cloudflare Under Attack, reject new connections, emergency email | - -### Mirage Shield Modes - -Mirage Shield is the attacker deflection shield with 4 operating modes: - -| Mode | Meaning | Auto Trigger | -|------|---------|-------------| -| `OBSERVE` | Observe only, no intervention | Default mode | -| `FORTIFY` | Harden defenses | heat ≥ 78 or threat_score ≥ 85 | -| `MIRAGE` | Mirror deflection | resonance ≥ 72 with high-confidence attacker | -| `SHELTER` | Shelter mode | heat ≥ 82 and resonance ≥ 80, strict rate limiting | - -In `MIRAGE` and `SHELTER` modes, deterrence messages are sent to detected attacker IPs. - -### Self-Healing Triggers - -`AluerSelfHealingOrchestrator` triggers recovery when: - -| Condition | Threshold | Recovery Actions | -|-----------|-----------|-----------------| -| TPS emergency | < 12 TPS | `clear-lag` + `kill-entity` + low spawn rate | -| CPU emergency | > 92% | `clear-lag` first, soft restart if ineffective | -| Memory emergency | > 95% | `save-all` → notify players → soft restart | -| Bot Swarm | ≥ 15 concurrent fake players | `whitelist on` + block source IPs | - -All recovery actions are log-only when `dry-run=true`. - ---- - -## 🌐 API Reference - -### System Status API - -| Method | Path | Description | -|--------|------|-------------| -| `GET` | `/api/status` | System running status | -| `GET` | `/api/server/info` | Minecraft server info | -| `GET` | `/api/performance` | TPS / CPU / Memory metrics | -| `POST` | `/api/command/execute` | Execute RCON command (param: `command`) | - -### Security Posture API - -| Method | Path | Description | -|--------|------|-------------| -| `GET` | `/api/security/stats` | Security overview | -| `GET` | `/api/security/network/posture` | Network posture details | -| `GET` | `/api/security/network/offenders?limit=10` | High-risk IP list | -| `GET` | `/api/security/network/incidents?limit=20` | Security incident list | -| `GET` | `/api/security/network/ip?ip=1.2.3.4` | Single IP deep inspection | -| `POST` | `/api/security/network/quarantine` | Quarantine IP (`ip`, `actor`, `reason`) | -| `POST` | `/api/security/network/release` | Release IP (`ip`, `actor`, `reason`) | - -### Health Check API - -| Method | Path | Description | -|--------|------|-------------| -| `GET` | `/api/health` | Full health report (component status + system resources) | -| `GET` | `/api/health/live` | Liveness probe (K8s compatible) | -| `GET` | `/api/health/ready` | Readiness probe (RCON availability check) | - -### Notification & Report API - -| Method | Path | Description | -|--------|------|-------------| -| `GET` | `/api/attacks/recent?limit=20` | Recent attack records | -| `POST` | `/api/attacks/report` | Generate HTML attack report | -| `POST` | `/api/webhook/test` | Test Discord/Slack webhook | - -### Console Operations API - -| Method | Path | Description | -|--------|------|-------------| -| `GET` | `/api/console/overview` | Full operations overview | -| `GET` | `/api/console/stream/overview` | SSE real-time stream | -| `POST` | `/api/console/shield/engage` | Manual shield mode switch (`mode`, `reason`) | -| `POST` | `/api/console/quick-action` | Quick action (`backup-now` / `shield-mirage` / `shield-shelter`) | - -### SSH Gateway API - -| Method | Path | Description | -|--------|------|-------------| -| `POST` | `/api/console/ssh/handshake` | Sovereign handshake approval | -| `POST` | `/api/console/ssh/connect` | Establish SSH connection | -| `POST` | `/api/console/ssh/execute` | Execute remote command | -| `DELETE` | `/api/console/ssh/{sessionId}` | Disconnect SSH session | - -**SSH Gateway security design**: -1. **Sovereign Handshake**: Connection requires handshake approval based on current heat and risk score -2. **Command Guard**: Every command is reviewed by `CommandExecutionGuardService` -3. **Session Timeout**: Auto-disconnect after 30 minutes of inactivity -4. **Audit Sync**: All SSH operations logged to `SecurityAuditService` - -### Backup Management API - -| Method | Path | Description | -|--------|------|-------------| -| `GET` | `/api/backup/list` | Backup list | -| `POST` | `/api/backup/create` | Create backup (param: `name`) | - ---- - -## 🖥️ Web Console - -Aluer ships with a React 19 + Vite 6 SPA console (Nebula Console). - -### Features - -| Feature | Description | -|---------|-------------| -| Shield Control | One-click FORTIFY / MIRAGE / SHELTER / RECOVERY mode switching | -| Performance Trend | TPS / CPU / Memory / Players SparkBar visualization | -| Auto Refresh | Toggle + configurable interval (3s / 6s / 10s / 30s) | -| Health Panel | Collapsible, shows RCON/AI/Email/Security/Self-Healing UP/DOWN status | -| SSH Terminal | Remote node connection with command guard review | -| Module Monitor | Real-time status and signal values for 9 modules | -| Threat View | High-risk IP list with score, riskLevel, and details (up to 10) | -| Audit Filter | Real-time filtering of audit events, network incidents, shield transitions (up to 24) | - -### Real-Time Data Flow - -Frontend receives data via **SSE (Server-Sent Events)** with automatic polling fallback: - -``` -Browser ──EventSource──→ /api/console/stream/overview - │ - Pushes full overview JSON every 6s - (aggregated by AluerOperationsCenterService) - │ - SSE fails → auto-fallback to setInterval - polling /api/console/overview - │ - Auto-refresh toggle: 3s / 6s / 10s / 30s -``` - ---- - -## 🖧 Shell Command Reference - -Aluer provides a Spring Shell interactive terminal with natural language support. - -### AI Conversation - -```bash -aluer> ai test server # Run full server test -aluer> ai enable defense # Enable AI autonomous defense -aluer> ai check security status # Get security posture overview -aluer> ai analyze the lag # DeepSeek deep analysis -aluer> ask how to improve security # Free-form Q&A -``` - -### Basic Commands - -| Command | Example | Description | -|---------|---------|-------------| -| `help` | `help` | Show all available commands | -| `status` | `status` | Server status (process/CPU/memory/connections) | -| `test` | `test` / `test cpu` / `test memory` | Run tests | -| `metrics` | `metrics` / `metrics counters` | Performance metrics | - -### Security Management - -| Command | Example | Description | -|---------|---------|-------------| -| `security` | `security` / `security ddos` / `security firewall` | Security module status | -| `defense` | `defense` / `defense on` / `defense level high` | AI defense control | -| `network` | `network` / `network geoip 1.2.3.4` | Network analysis | - -### Player Management - -| Command | Example | Description | -|---------|---------|-------------| -| `kick` | `kick PlayerName` | Kick player | -| `ban` | `ban PlayerName` / `ban PlayerName cheating` | Ban player | -| `unban` | `unban PlayerName` | Unban player | - -### Operations - -| Command | Example | Description | -|---------|---------|-------------| -| `backup` | `backup create` / `backup status` | Backup management | -| `world` | `world load world_nether` | World management | -| `alert` | `alert test` / `alert send server anomaly` | Email alerts | -| `audit` | `audit recent 20` / `audit summary` | Security audit | -| `tasks` | `tasks start` | Scheduled task management | - ---- - -## 🔧 Developer Guide - -### Project Structure - -``` -Aluer/ -├── src/main/java/com/aluer/ -│ ├── ai/ # AI Decision Engine (7 classes) -│ ├── kernel/ # Kernel Engine (3 classes) -│ ├── security/ # Security Modules (33 classes) -│ ├── console/ # Operations Control (4 classes) -│ ├── monitor/ # Monitoring Collection (4 classes) -│ ├── service/ # Core Services (4 classes) -│ ├── web/ # Web Layer (5 classes) -│ ├── notification/ # Notification & Reports (2 classes) -│ ├── config/ # Configuration -│ ├── model/ # Data Models -│ ├── terminal/ # Shell Terminal -│ ├── command/ # Shell Commands -│ ├── alert/ # Alerts -│ ├── backup/ # Backup -│ ├── anticheat/ # Anti-Cheat -│ ├── vpn/ # VPN Detection -│ ├── chat/ # Chat Filter -│ ├── punishment/ # Punishment -│ ├── audit/ # Security Audit -│ ├── world/ # World Management -│ ├── metrics/ # Metrics Collection -│ ├── profiler/ # Performance Profiler -│ ├── schedule/ # Scheduled Tasks -│ ├── export/ # Data Export -│ └── ServerGuardApplication.java -│ -├── src/main/resources/ -│ ├── application.yml -│ ├── banner.txt -│ ├── logback.xml -│ └── static/ -│ -├── src/test/java/com/aluer/ # Tests (9 files) -├── frontend/ # React Frontend -├── systemd/ # Systemd Service Files -├── docs/ # Documentation -├── apache-maven-3.9.6/ # Bundled Maven -└── pom.xml -``` - -### Build & Run - -```bash -# Full build (includes frontend) -./apache-maven-3.9.6/bin/mvn clean package -DskipTests - -# Compile only -./apache-maven-3.9.6/bin/mvn compile - -# Run -java -jar target/serverguard.jar -``` - -### Frontend Development - -```bash -cd frontend -npm install -npm run dev # Dev server at http://localhost:4173 -npm run build # Production build → ../src/main/resources/static/ -``` - -### Running Tests - -```bash -# All tests -./apache-maven-3.9.6/bin/mvn test - -# Specific test class -./apache-maven-3.9.6/bin/mvn test -Dtest=AluerKernelEngineTest -``` - -### Adding a New Security Module - -Each security module follows a consistent convention: - -1. Create a new class in `com.aluer.security` -2. Inject `ServerGuardConfig` via constructor -3. Implement `getPosture()` for Kernel consumption -4. Register in `NetworkThreatFusionService` (if network-related) -5. Aggregate in `AluerOperationsCenterService.buildOverview()` (if needed in console) -6. Add config node in `application.yml` - ---- - -## ❓ FAQ - -
-How do I verify AI is working? - -```bash -aluer> ask Hello -``` - -If you get an AI response, DeepSeek is configured correctly. Or check logs: - -```bash -tail -f /var/log/serverguard.log | grep DeepSeek -``` -
- -
-Not receiving email alerts? - -1. Verify `username`/`password` in email config -2. QQ email requires **authorization code** not login password -3. Check spam folder -4. Run `alert test` to send a test email -
- -
-Tips for first deployment? - -Enable **dry-run mode** first: - -```yaml -serverguard: - security: - host-enforcement: - dry-run: true - cloud-edge: - dry-run: true - self-healing: - dry-run: true -``` - -Observe for 1-2 days before disabling dry-run. -
- -
-Why two decision engines? Won't they conflict? - -No, they're complementary: -- **Sovereign (DeepSeek)**: excels at complex, never-seen attack patterns; 2-5s latency -- **Kernel (rule engine)**: <1ms response, 100% predictable, but can't handle unknown patterns - -When outputs disagree, `AIAutonomousService` (L3) resolves based on `autonomy.deepseek-dominant` config. `SecurityOrchestrationService` provides final safety net — no operation exceeds `max-actions-per-hour`. -
- -
-Performance overhead? - -Tested on 2-core 4GB VPS: -- JVM resident memory: ~180-250 MB (Spring Boot + all services) -- CPU idle: <2% (monitoring and Pulse loops) -- DeepSeek API call CPU: ~5% (mainly network I/O wait) -- No impact on Minecraft server performance (async RCON communication) -
- ---- - -## 📄 License - -This project is open-sourced under **Apache License 2.0**. See [LICENSE](LICENSE) for full text. - -| Clause | Description | -|:-------|:------------| -| ✅ **Permitted** | Commercial use, modification, distribution, patent use, private use | -| ⚠️ **Required** | Include license and copyright notice, mark changed files | -| ❌ **Limited** | No warranty, authors not liable for damages | - ---- - -## 🌟 Support the Project - -If Aluer ServerGuard helps you, please consider: - -

- Star -   - Fork -   - Bug -   - Discuss -

- ---- - -

🏆 Contributors

- -

- - - -

- -

- Made with ❤️ by the Aluer community — defending Minecraft servers worldwide -

- ---- - -

- - Repo Size - - - License - - Built With -
- Aluer ServerGuard v1.0.0 — Autonomous protection for your Minecraft community -

+Proprietary. All rights reserved. diff --git a/docs/DEVELOPER.md b/docs/DEVELOPER.md index ae2f942..4ccc82d 100644 --- a/docs/DEVELOPER.md +++ b/docs/DEVELOPER.md @@ -1,773 +1,1022 @@ -# Aluer ServerGuard V4.0 — 开发参考手册 +# Aluer ServerGuard V5.0 -- 开发者参考手册 ## 版本信息 | 项目 | 内容 | |------|------| -| 版本号 | V4.0 | -| 发布日期 | 2026-05-10 | +| 版本号 | V5.0 (含 V5.1/V5.2/V5.3 子版本) | +| 更新日期 | 2026-05-16 | +| Java 版本 | 21 | +| Spring Boot | 3.2.0 | | 构建工具 | Apache Maven 3.9.6 (bundled) | -| 运行环境 | Java 17+, Spring Boot 3.2.0 | -| 许可证 | Apache 2.0 | +| PaperMC API | 1.21.1-R0.1-SNAPSHOT | --- ## 目录 -1. [技术架构](#1-技术架构) -2. [项目结构](#2-项目结构) -3. [模块详解](#3-模块详解) -4. [核心设计模式](#4-核心设计模式) -5. [配置体系](#5-配置体系) -6. [API 参考](#6-api-参考) -7. [CLI 命令系统](#7-cli-命令系统) -8. [测试策略](#8-测试策略) -9. [构建与部署](#9-构建与部署) -10. [安全机制层次](#10-安全机制层次) -11. [扩展开发指南](#11-扩展开发指南) +1. [系统架构](#系统架构) +2. [项目结构](#项目结构) +3. [核心设计模式](#核心设计模式) +4. [添加新反作弊模块](#添加新反作弊模块) +5. [事件监听器模式](#事件监听器模式) +6. [Agent 通信协议详解](#agent-通信协议详解) +7. [配置系统](#配置系统) +8. [ML/AI 集成](#mlai-集成) +9. [测试规范](#测试规范) +10. [代码风格指南](#代码风格指南) +11. [构建系统](#构建系统) --- -## 1. 技术架构 +## 系统架构 -### 1.1 总体架构 - -Aluer ServerGuard 采用分层架构设计,自底向上分为基础层、安全层、AI 决策层与交互层: +### 整体架构 ``` -┌──────────────────────────────────────────────────────┐ -│ 交互层 (Interaction) │ -│ AITerminal (Spring Shell) │ Dashboard (REST API) │ -├──────────────────────────────────────────────────────┤ -│ AI 决策层 (Intelligence) │ -│ DeepSeekClient │ AnomalyDetector │ StrategyEngine│ -├──────────────────────────────────────────────────────┤ -│ 安全层 (Security) │ -│ ┌──────────┬──────────┬──────────┬──────────┐ │ -│ │ 网络防御 │ 主机安全 │ 应用防护 │ 合规审计 │ │ -│ │ DDoS/IDS │ 进程/内存 │ WAF/CSP │ 取证/报告 │ │ -│ └──────────┴──────────┴──────────┴──────────┘ │ -├──────────────────────────────────────────────────────┤ -│ 基础层 (Foundation) │ -│ KernelEngine │ TaskBus │ SelfHealing │ Config │ -└──────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| Aluer ServerGuard V5.0 | +| | +| 部署模式一:Plugin 内嵌模式(推荐) | +| ┌─────────────────────────────────────────────────────────────┐ | +| │ Minecraft PaperMC JVM │ | +| │ ┌──────────────┐ WebSocket ┌──────────────────┐ │ | +| │ │ AluerPlugin │ ◄═══════════════► │ ServerGuard │ │ | +| │ │ (Paper插件) │ ws://:8080/agent │ Spring Boot App │ │ | +| │ │ │ │ │ │ | +| │ │ Bukkit事件 → │ ──EVENT/METRICS──► │ 安全分析引擎 │ │ | +| │ │ 监听器 │ │ ML/AI模块 │ │ | +| │ │ │ ◄──COMMAND/CONFIG─ │ DeepSeek集成 │ │ | +| │ │ 命令执行器 ← │ │ Web Dashboard │ │ | +| │ └──────────────┘ └──────────────────┘ │ | +| └─────────────────────────────────────────────────────────────┘ | +| | +| 部署模式二:External 外部监控模式 | +| ┌──────────────────┐ RCON + 日志监控 ┌──────────────┐ | +| │ PaperMC Server │ ◄═══════════════════► │ ServerGuard │ | +| │ (独立JVM) │ │ (独立JVM) │ | +| └──────────────────┘ └──────────────┘ | ++------------------------------------------------------------------+ ``` -### 1.2 技术栈 - -| 层次 | 技术 | 用途 | -|------|------|------| -| 运行时 | Java 17 | 核心语言 | -| 框架 | Spring Boot 3.2.0 | 应用容器、依赖注入、配置管理 | -| CLI | Spring Shell 3.1.3 | 交互式命令行终端 | -| Web | Spring Boot Web (Tomcat) | REST API 服务 | -| 构建 | Maven 3.9.6 | 依赖管理、打包 | -| AI | DeepSeek API | 威胁分析、根因诊断 | -| 数学 | Commons Math 3.6.1 | 孤立森林、统计计算 | -| SSH | JSch 0.2.20 | 远程 SSH 连接 | -| 序列化 | Gson 2.10.1 | JSON 处理 | -| 邮件 | javax.mail 1.6.2 | 告警通知 | -| 前端 | React 19.1 + Vite 6.3 | Web 控制台 | - -### 1.3 数据流 +### 数据流向 ``` -Minecraft Server ──> ProcessMonitor ──> MetricsService ──> AnomalyDetector - │ │ │ │ - │ LogMonitor │ DeepSeekClient - │ │ │ │ - └── RconClient ──> AutoExecutor <── AIStrategyEngine <──┘ - │ - Dashboard API ──> Web Console +Bukkit Events + │ + ▼ +┌─────────────┐ AgentMessage.buildMessage() ┌──────────────┐ +│ Event │ ─────────────────────────────────► │ Security │ +│ Listeners │ JSON via WebSocket │ Modules │ +│ (9个监听器) │ │ (123个模块) │ +└─────────────┘ │ │ + │ ┌─────────┐ │ + │ │ ML/AI │ │ + │ │ Engine │ │ + │ └────┬────┘ │ + │ │ │ + │ ┌────▼────┐ │ + │ │DeepSeek │ │ + │ │Analysis │ │ + │ └────┬────┘ │ + │ │ │ + │ ┌────▼────┐ │ + │ │Autonomy │ │ + │ │/Shield │ │ + │ └────┬────┘ │ + └──────│───────┘ + │ + AgentMessage.buildCommand() + │ + ▼ + ┌──────────────┐ + │ AluerPlugin │ + │ Command │ + │ Executor │ + │ (Bukkit API) │ + └──────────────┘ ``` --- -## 2. 项目结构 +## 项目结构 ``` -AluerIII/ -├── pom.xml # Maven 项目配置 -├── apache-maven-3.9.6/ # 内置 Maven(无需系统安装) -├── src/ -│ ├── main/java/com/aluer/ -│ │ ├── ServerGuardApplication.java # Spring Boot 启动入口 -│ │ ├── ai/ # AI 智能分析模块 (7 files) -│ │ ├── alert/ # 邮件告警 (1 file) -│ │ ├── anticheat/ # 反作弊集成 (1 file) -│ │ ├── audit/ # 安全审计 (1 file) -│ │ ├── backup/ # 自动备份 (1 file) -│ │ ├── chat/ # 聊天过滤 (1 file) -│ │ ├── command/ # Shell 命令 (2 files) -│ │ ├── config/ # 配置管理 (2 files) -│ │ ├── console/ # 运维控制台 (4 files) -│ │ ├── controller/ # 测试端点 (1 file) -│ │ ├── export/ # 数据导出 (1 file) -│ │ ├── kernel/ # 内核引擎 (3 files) -│ │ ├── metrics/ # 指标采集 (1 file) -│ │ ├── model/ # 数据模型 (3 files) -│ │ ├── monitor/ # 系统监控 (4 files) -│ │ ├── notification/ # Webhook/报告 (2 files) -│ │ ├── profiler/ # 性能分析 (1 file) -│ │ ├── punishment/ # 玩家处罚 (1 file) -│ │ ├── schedule/ # 定时任务 (1 file) -│ │ ├── security/ # 安全引擎 (85 files) -│ │ ├── service/ # 核心服务 (4 files) -│ │ ├── terminal/ # AI 终端 (1 file) -│ │ ├── vpn/ # VPN 检测 (1 file) -│ │ ├── web/ # Web 控制台 (5 files) -│ │ └── world/ # 世界管理 (1 file) -│ ├── main/resources/ -│ │ └── application.yml # 全局配置 -│ └── test/java/com/aluer/ # 测试 (12 files, 114 cases) -├── docs/ -│ ├── DEVELOPER.md # 本文档 -│ ├── USER_MANUAL.md # 用户手册 -│ └── PROJECT_SUMMARY.md # 功能拆解 -├── frontend/ # React Web 控制台源码 -├── forensics/ # 取证输出目录 -├── release/ # 发布产物 -└── README.md # 项目概览 +src/main/java/com/aluer/ +│ +├── ServerGuardApplication.java # Spring Boot 主入口 +│ +├── config/ +│ └── ServerGuardConfig.java # 完整配置类(1273行) +│ ├── MinecraftConfig # Minecraft 进程配置 +│ ├── MonitorConfig # 监控阈值配置 +│ ├── AlertConfig # 告警(邮件)配置 +│ ├── AiConfig # AI/ML 配置 +│ │ └── DeepSeekConfig # DeepSeek 大模型配置 +│ │ └── AutoExecuteConfig # 自动执行配置 +│ ├── SecurityConfig # 安全总配置 +│ │ ├── MinecraftDefenseConfig # Minecraft 协议层防御 +│ │ ├── DDoSDefenseConfig # DDoS 防御阈值 +│ │ ├── AntiIntrusionConfig # 入侵检测配置 +│ │ ├── HostEnforcementConfig # 主机层强制 +│ │ ├── CloudEdgeConfig # Cloudflare 边缘 +│ │ ├── ThreatFeedsConfig # 威胁情报源 +│ │ ├── OrchestrationConfig # 多层编排 +│ │ ├── AutomationConfig # 自动化调度 +│ │ ├── AutonomyConfig # 自主决策 +│ │ ├── ShieldConfig # 护盾配置 +│ │ ├── KernelConfig # 内核/脉冲配置 +│ │ ├── TaskBusConfig # 任务总线 +│ │ ├── SelfHealingConfig # 自愈配置 +│ │ └── SuperEvolutionConfig # 全部模块开关(70+开关) +│ ├── DashboardConfig # Web 控制台 +│ ├── AnnouncementConfig # 公告 +│ ├── AfkConfig # AFK 管理 +│ ├── ChatFilterConfig # 聊天过滤 +│ ├── BackupConfig # 备份配置 +│ └── ScheduleConfig # 定时任务 +│ +├── model/ +│ └── AlertType.java # 告警类型枚举(75种) +│ +├── agent/ +│ └── AgentMessage.java # Agent 通信协议 +│ # 常量:TYPE_EVENT, TYPE_METRICS, TYPE_ALERT, +│ # TYPE_HEARTBEAT, TYPE_HANDSHAKE, TYPE_COMMAND_RESULT, +│ # TYPE_COMMAND, TYPE_CONFIG, TYPE_SHUTDOWN +│ # 命令:CMD_BAN_IP, CMD_BAN_PLAYER, CMD_KICK, +│ # CMD_CLEAR_LAG, CMD_SET_SPAWN_RATE, ... +│ # 事件:EVENT_PLAYER_JOIN, EVENT_PLAYER_MOVE, +│ # EVENT_COMBAT_ATTACK, EVENT_BLOCK_BREAK, ... +│ +├── security/ # 安全模块(123个Java文件) +│ ├── AntiKillAuraService.java # 杀戮光环检测 +│ ├── AntiReachService.java # 超距攻击检测 +│ ├── AntiSpeedService.java # 速度异常检测 +│ ├── AntiCriticalsService.java # 暴击检测 +│ ├── AntiAutoCrystalService.java # 水晶自动检测 +│ ├── ... # 120+ more +│ └── ZeroTrustArchitectureService.java +│ +├── ml/ # ML/AI 模块(4个文件) +│ ├── BehavioralProfilingEngine.java # 行为画像 +│ ├── CombatPatternRecognizer.java # 战斗模式识别 +│ ├── MovementPatternAnalyzer.java # 移动模式分析 +│ └── ThreatScoreAggregator.java # 威胁评分聚合 +│ +├── plugin/ # Paper 插件实现 +│ ├── AluerPlugin.java # 插件主类 (extends JavaPlugin) +│ ├── AluerCommandExecutor.java # 命令注册器 +│ ├── bridge/ +│ │ ├── AgentWebSocketClient.java # WebSocket 客户端 +│ │ ├── DataBridge.java # 数据格式转换 +│ │ └── InternalCommandExecutor.java # Bukkit API命令执行 +│ └── listener/ # Bukkit 事件监听器 +│ ├── BlockEventListener.java # 方块事件 +│ ├── ChatEventListener.java # 聊天事件 +│ ├── CombatEventListener.java # 战斗事件 +│ ├── CommandEventListener.java # 命令事件 +│ ├── EntityEventListener.java # 实体事件 +│ ├── InventoryEventListener.java # 背包事件 +│ ├── PacketEventListener.java # 原始包事件 +│ ├── PlayerEventListener.java # 玩家事件 +│ └── WorldEventListener.java # 世界事件 +│ +├── websocket/ # WebSocket 服务端 +└── controller/ + └── TestController.java # 测试端点 ``` --- -## 3. 模块详解 +## 核心设计模式 -### 3.1 AI 智能分析模块 (`com.aluer.ai`) +### 1. 双构造函数模式 -负责威胁感知、异常检测、趋势预测与智能决策。 - -| 类名 | 功能 | 核心算法 | -|------|------|----------| -| `AIAutonomousService` | 自主威胁感知与自动防御触发 | 正则模式匹配、流量时序分析 | -| `AIStrategyEngine` | 根据威胁严重程度匹配防御策略 | 规则引擎 | -| `DeepSeekClient` | DeepSeek API 集成,深度威胁分析 | LLM 推理 | -| `AnomalyDetector` | 多指标异常检测 | 孤立森林 (Isolation Forest) | -| `AttackDetector` | 协同攻击检测 | 关联分析 | -| `TimeSeriesPredictor` | TPS/内存趋势预测 | 滑动窗口 + 线性回归 | -| `AdaptiveThreshold` | 动态告警阈值调整 | 历史基线学习 | -| `AluerSovereignEngine` | 自主决策总控引擎 | 多信号融合 | - -### 3.2 Kernel 内核模块 (`com.aluer.kernel`) - -系统级信号处理与任务调度核心。 - -| 类名 | 功能 | -|------|------| -| `AluerKernelEngine` | 内核脉冲引擎,周期性采集系统信号,维护信号日志与回响队列 | -| `AluerKernelTaskBus` | 异步任务总线,支持任务排队、分发与历史记录 | -| `AluerSelfHealingOrchestrator` | 自愈编排器,检测异常后自动执行恢复剧本(重启/备份/白名单) | - -### 3.3 安全引擎 (`com.aluer.security`) - -85 个安全服务类,分为以下子类: - -#### 3.3.1 网络安全防御 - -| 服务类 | 防护目标 | 关键技术 | -|--------|----------|----------| -| `DDoSProtectionService` | DDoS 攻击 | SYN/HTTP/UDP/ICMP Flood 检测 | -| `DDoSDefenseCoordinator` | 多层 DDoS 协同防御 | 流量清洗调度 | -| `IntrusionDetectionService` | 入侵检测 | 行为基线偏离 | -| `IntrusionPreventionSystem` | 入侵阻断 | 实时封禁 | -| `FirewallService` | 主机防火墙 | iptables/ufw 规则管理 | -| `NetworkMonitorService` | 网络流量监控 | 带宽统计、连接追踪 | -| `PortScanDetectionService` | 端口扫描检测 | 连接频率 + 端口序列分析 | -| `IPReputationService` | IP 信誉评估 | 黑名单 + 行为评分 | -| `GeoIPService` | IP 地理定位 | GeoIP 数据库查询 | -| `GeoBlockService` | 地理区域封锁 | 国家/地区级拦截 (v3.3) | -| `ConnectionThrottleService` | 连接速率限制 | 多时间窗口 + 递增延迟 (v3.3) | -| `TrafficAnalysisService` | 流量深度分析 | 协议识别、异常流量模式 | -| `TrafficShapingService` | 流量整形 | 带宽限制、优先级队列 | -| `LoadBalancerService` | 负载均衡 | 连接分发 | -| `NetworkThreatFusionService` | 威胁信号融合 | 多源威胁情报合并 | -| `NetworkSegmentationService` | 网络隔离 | 微隔离策略 | -| `NetworkSnifferService` | 网络嗅探 | 原始数据包捕获 | -| `PacketInspectionService` | 深度包检测 | 载荷特征匹配 | -| `ProtocolAnalysisService` | 协议分析 | Minecraft 协议异常 | -| `FlowAnalyzerService` | 流量分析器 | NetFlow/sFlow 分析 | -| `DistributedAttackMitigationService` | 分布式攻击缓解 | 多节点协同防御 | -| `ContainerSecurityService` | 容器安全 | Docker/K8s 安全策略 | - -#### 3.3.2 应用层安全 - -| 服务类 | 防护目标 | 关键技术 | -|--------|----------|----------| -| `WebApplicationFirewall` | Web 应用攻击 | SQLi/XSS/路径遍历过滤 | -| `WafRequestFilter` | HTTP 请求过滤 | Servlet Filter 拦截 | -| `JwtAuthService` | API 身份认证 | JWT 令牌签发/验证 | -| `BruteForceProtectionService` | 暴力破解防护 | 多时间窗口登录失败计数 | -| `AntiBotDetectionService` | 机器人检测 | 名称模式/加入速率/IP 关联 | -| `CSPEnforcementService` | 内容安全策略 | 8 种 HTTP 安全响应头 | -| `XXEProtectionService` | XML 外部实体防护 | Entity 注入检测 | -| `SSRFProtectionService` | 服务端请求伪造防护 | 内网 IP/云元数据/编码绕过 | -| `SessionManagementService` | 会话管理 | 超时/并发/固定 | -| `APIRateLimitService` | API 速率限制 | 令牌桶算法 | -| `RateLimitService` | 通用速率限制 | 滑动窗口 | -| `CommandExecutionGuardService` | 命令执行防护 | 注入检测 | - -#### 3.3.3 主机与端点安全 - -| 服务类 | 防护目标 | 关键技术 | -|--------|----------|----------| -| `ReverseShellDetectionService` | 反向 Shell 检测 | 50+ Shell 模式匹配 | -| `ARPSpoofDetectionService` | ARP 欺骗检测 | MAC 变更/网关伪造监测 | -| `DNSTunnelDetectionService` | DNS 隧道检测 | 香农熵/Base32 编码/可疑 TLD | -| `ExploitSignatureService` | 漏洞特征检测 | 15 种已知漏洞模式匹配 | -| `DatabaseFirewallService` | 数据库防火墙 | SQL 注入/联合查询/时间盲注 | -| `DataLossPreventionService` | 数据防泄漏 | 12 种敏感信息规则/自动脱敏 | -| `MemoryProtectionService` | JVM 内存保护 | 堆/GC/内存泄漏监控 | -| `ProcessInjectionDetectionService` | 进程注入检测 | /proc 扫描/线程异常检测 | -| `SecureFileDeletionService` | 安全文件删除 | 多道覆写 (DoD 5220.22-M) | -| `ForensicsCollectorService` | 取证数据收集 | 进程/网络/日志快照 | -| `IncidentResponseService` | 事件响应自动化 | 5 种预定义响应剧本 | -| `ThreatHuntingService` | 威胁狩猎 | 10 种狩猎定义/5 个 IOC 类别 | -| `ComplianceScannerService` | 合规扫描 | 7 类 20+ 检查项 | -| `SecurityBaselineHardeningService` | 安全基线硬化 | 系统配置加固 | -| `SecurityAutomationScheduler` | 安全自动化调度 | 定时安全任务 | -| `SecurityOrchestrationService` | 安全编排 | 多模块协同 | -| `FileIntegrityMonitorService` | 文件完整性监控 | 哈希比对 | -| `EndpointDetectionResponseService` | 端点检测响应 | 行为监控 | -| `HostEnforcementService` | 主机强制策略 | 内核级防火墙 | -| `HostIntrusionCountermeasureService` | 主机入侵对策 | 自动隔离 | -| `LogAnalysisService` | 日志分析 | 模式匹配与异常检测 | -| `LogCorrelationService` | 日志关联 | 多源日志关联分析 | -| `SIEMService` | 安全信息事件管理 | 事件关联引擎 | -| `EncryptionService` | 加密服务 | AES/RSA 操作 | -| `SSLMonitorService` | SSL 证书监控 | 到期检测 | -| `SSLTLSCertificateService` | SSL/TLS 管理 | 证书生命周期 | - -#### 3.3.4 Minecraft 专属安全 - -| 服务类 | 防护目标 | 关键技术 | -|--------|----------|----------| -| `MinecraftProtocolSecurityService` | 协议层安全 | NBT/数据包校验 | -| `AntiGriefDetectionService` | 反破坏检测 | 方块破坏率/TNT/纵火/偷箱 | -| `AntiXrayDetectionService` | X-ray 透视检测 | 钻石矿比例/直线挖掘/暗处精准 | -| `AntiFlyDetectionService` | 飞行外挂检测 | 垂直/水平速度阈值/悬空时间 | -| `AntiDupeDetectionService` | 物品复制检测 | 堆叠异常/高价值暴涨/9 种复制模式 | -| `CrashExploitProtectionService` | 崩溃漏洞防护 | 超大包/NBT 炸弹/书与笔攻击 | -| `LagMachineDetectionService` | 卡服机检测 | Observer 链/TNT 堆/红石密度 | -| `PlayerSessionValidationService` | 玩家会话验证 | UUID 格式/离线模式/快速切换 (v3.3) | -| `PluginVerificationService` | 插件完整性校验 | SHA-256/文件大小/恶意名称 (v3.3) | -| `AntiSkinSpoofService` | 皮肤伪造检测 | 模型异常/URL 检测/变更频率 (v3.3) | - -#### 3.3.5 运维安全 - -| 服务类 | 功能 | -|--------|------| -| `BackupSecurityService` | 备份安全策略管理 | -| `BackupIntegrityService` | 备份完整性校验 SHA-256 (v3.3) | -| `HoneypotService` | 蜜罐诱捕系统 | -| `ZeroTrustArchitectureService` | 零信任架构 | -| `CloudflareIntegrationService` | Cloudflare CDN 联动 | -| `ThreatIntelligenceService` | 威胁情报中心 | -| `AdvancedMalwareDetectionService` | 恶意软件扫描 | -| `DNSSecurityService` | DNS 安全 | - -### 3.4 监控模块 (`com.aluer.monitor`) - -| 类名 | 监控目标 | 采集指标 | -|------|----------|----------| -| `ResourceMonitor` | 系统资源 | CPU/内存/磁盘/TPS | -| `LogMonitor` | 服务端日志 | 异常堆栈/安全事件 | -| `ProcessMonitor` | Minecraft 进程 | 存活状态/重启触发 | -| `ConnectionMonitor` | 网络连接 | 连接数/连接频率 | - -### 3.5 核心服务 (`com.aluer.service`) - -| 类名 | 功能 | -|------|------| -| `ServerGuardService` | 系统总控,协调所有模块启动与调度 | -| `AutoExecutor` | 自动化指令执行,将 AI 决策转为服务器操作 | -| `RconClient` | RCON 协议客户端,安全下发 Minecraft 指令 | - -### 3.6 Web 控制台 (`com.aluer.web`) - -| 类名 | 功能 | -|------|------| -| `DashboardController` | 主 API 控制器,48 个 REST 端点 | -| `ConsoleStreamController` | 控制台实时流 | -| `OperationsConsoleController` | 运维操作 API | -| `HealthService` | 健康检查服务 | -| `RequestLoggingFilter` | HTTP 请求日志过滤器 | - ---- - -## 4. 核心设计模式 - -### 4.1 结果封装模式 - -所有安全服务采用**内部静态结果类 + 静态工厂方法**模式: +每个安全模块 Service 类同时提供两个构造函数,确保测试友好性和生产注入兼容性: ```java -public class SomeSecurityService { - public static class DetectionResult { - private final boolean blocked; - private final List reasons; +@Service +public class AntiKillAuraService { - private DetectionResult(boolean blocked, List reasons) { ... } - - public static DetectionResult clean() { return new DetectionResult(false, List.of()); } - public static DetectionResult blocked(List reasons) { return new DetectionResult(true, reasons); } - - public boolean isBlocked() { return blocked; } - public List getReasons() { return reasons; } - } -} -``` - -优势:不可变、类型安全、语义明确、易于测试断言。 - -### 4.2 双构造函数模式 - -所有安全服务实现双构造函数以支持 Spring 注入和单元测试: - -```java -public class SomeSecurityService { private final ServerGuardConfig config; - // 无参构造函数 — 测试用 - public SomeSecurityService() { - this(new ServerGuardConfig()); + /** 无参构造函数:用于单元测试,使用默认配置 */ + public AntiKillAuraService() { + this.config = new ServerGuardConfig(); } - // 参数化构造函数 — Spring 注入 + /** @Autowired 构造函数:用于生产环境,Spring 自动注入 */ @Autowired - public SomeSecurityService(ServerGuardConfig config) { + public AntiKillAuraService(ServerGuardConfig config) { this.config = config; } + + // ... 检测逻辑 } ``` -### 4.3 开关控制模式 +### 2. 静态工厂方法模式 -所有 31 个扩展安全模块通过 `ServerGuardConfig` 统一控制,方法入口处检查: +检测结果使用内部静态类 + 静态工厂方法构建,避免直接 new: ```java -public DetectionResult detect(String input) { - if (!config.getSecurity().getSuperEvolution().isXxx()) { - return DetectionResult.clean(); // 模块关闭,返回安全结果 +public static class DetectionResult { + public enum Status { CLEAN, BLOCKED, FLAGGED } + + private final Status status; + private final String reason; + private final double confidence; + + private DetectionResult(Status status, String reason, double confidence) { + this.status = status; + this.reason = reason; + this.confidence = confidence; } - // ... 实际检测逻辑 + + public static DetectionResult clean() { + return new DetectionResult(Status.CLEAN, null, 0.0); + } + + public static DetectionResult blocked(String reason, double confidence) { + return new DetectionResult(Status.BLOCKED, reason, confidence); + } + + public static DetectionResult flagged(String reason, double confidence) { + return new DetectionResult(Status.FLAGGED, reason, confidence); + } + + // getters... } ``` -### 4.4 配置层次绑定 +### 3. ConcurrentHashMap 玩家追踪 -使用 `@ConfigurationProperties(prefix = "serverguard")` 实现类型安全的 YAML 到 Java 映射,支持嵌套静态内部类,每个层级对应 YAML 的一级缩进。 +所有安全模块使用 `ConcurrentHashMap` 以玩家名称为键追踪行为数据,确保线程安全: ---- - -## 5. 配置体系 - -### 5.1 配置层级 - -``` -serverguard -├── minecraft # Minecraft 服务端连接 -│ └── rcon # RCON 协议配置 -├── monitor # 监控阈值 -├── alert # 告警配置 -│ └── email # 邮件服务 -│ └── rate-limit -├── ai # AI 模块配置 -│ └── deepseek # DeepSeek API -│ └── auto-execute -├── security # 安全模块配置 -│ ├── anti-intrusion -│ │ └── file-integrity -│ ├── host-enforcement -│ ├── cloud-edge -│ ├── orchestration -│ ├── autonomy -│ ├── shield -│ ├── kernel -│ ├── task-bus -│ ├── self-healing -│ └── super-evolution # 31 个扩展模块独立开关 -├── dashboard # Web 控制台 -│ └── ssh-gateway -├── webhook # 通知集成 -└── report # 报告输出 +```java +private final Map> playerAttackHistory = new ConcurrentHashMap<>(); +private final Map> playerAngleHistory = new ConcurrentHashMap<>(); ``` -### 5.2 Super Evolution 模块开关 (V4.0 全部 31 个) +### 4. AtomicLong 统计计数 -所有开关均为 `boolean` 类型,默认值 `true`,位于 `serverguard.security.super-evolution` 路径下: +使用 `AtomicLong` 进行线程安全的统计计数: -| 配置键 | 模块名称 | 版本 | -|--------|----------|------| -| `jwt-auth` | JWT 身份认证 | v3.1 | -| `brute-force` | 暴力破解防护 | v3.1 | -| `anti-bot` | 反机器人检测 | v3.1 | -| `reverse-shell` | 反向 Shell 检测 | v3.1 | -| `arp-spoof` | ARP 欺骗检测 | v3.1 | -| `dns-tunnel` | DNS 隧道检测 | v3.1 | -| `exploit-signature` | 漏洞签名检测 | v3.1 | -| `ssrf` | SSRF 防护 | v3.1 | -| `xxe` | XXE 防护 | v3.1 | -| `csp` | CSP 安全头 | v3.1 | -| `database-firewall` | 数据库防火墙 | v3.1 | -| `dlp` | 数据防泄漏 | v3.1 | -| `memory-protection` | 内存保护 | v3.1 | -| `process-injection` | 进程注入检测 | v3.1 | -| `secure-delete` | 安全文件删除 | v3.1 | -| `forensics` | 取证收集 | v3.1 | -| `incident-response` | 事件响应 | v3.1 | -| `threat-hunting` | 威胁狩猎 | v3.1 | -| `compliance` | 合规扫描 | v3.1 | -| `anti-grief` | 反破坏检测 | v3.1 | -| `anti-xray` | X-ray 检测 | v3.2 | -| `anti-fly` | 飞行外挂检测 | v3.2 | -| `anti-dupe` | 物品复制检测 | v3.2 | -| `crash-exploit` | 崩溃漏洞防护 | v3.2 | -| `lag-machine` | 卡服机检测 | v3.2 | -| `geo-block` | 地理 IP 封锁 | v3.3 | -| `session-validation` | 会话验证 | v3.3 | -| `plugin-verification` | 插件校验 | v3.3 | -| `connection-throttle` | 连接速率限制 | v3.3 | -| `backup-integrity` | 备份完整性 | v3.3 | -| `anti-skin-spoof` | 皮肤伪造检测 | v3.3 | +```java +private final AtomicLong totalChecks = new AtomicLong(0); +private final AtomicLong flaggedCount = new AtomicLong(0); +``` ---- +### 5. 配置驱动开关 -## 6. API 参考 +每个模块通过 `SuperEvolutionConfig` 中的独立开关控制启用/禁用: -所有 API 基于 Spring Boot REST,前缀 `/api`。以下按功能域分组: - -### 6.1 系统状态 - -| 方法 | 路径 | 说明 | -|------|------|------| -| GET | `/api/health` | 系统健康检查 | -| GET | `/api/status` | 综合状态概览 | -| GET | `/api/status/ai` | AI 模块状态 | -| GET | `/api/status/monitor` | 监控模块状态 | - -### 6.2 安全防御 - -| 方法 | 路径 | 说明 | -|------|------|------| -| GET | `/api/security/ddos/status` | DDoS 防御状态 | -| GET | `/api/security/firewall/status` | 防火墙状态 | -| GET | `/api/security/ids/status` | 入侵检测状态 | -| GET | `/api/security/ips/status` | 入侵防御状态 | -| GET | `/api/security/waf/status` | WAF 状态 | -| GET | `/api/security/ip-reputation/status` | IP 信誉状态 | -| GET | `/api/security/geo-block/status` | 地理封锁状态 (v3.3) | -| GET | `/api/security/session-validation/status` | 会话验证状态 (v3.3) | -| GET | `/api/security/plugin-verification/status` | 插件校验状态 (v3.3) | -| GET | `/api/security/connection-throttle/status` | 连接限制状态 (v3.3) | -| GET | `/api/security/backup-integrity/status` | 备份完整性状态 (v3.3) | -| GET | `/api/security/anti-skin-spoof/status` | 反皮肤伪造状态 (v3.3) | - -### 6.3 安全检测(应用层) - -| 方法 | 路径 | 说明 | -|------|------|------| -| GET | `/api/security/jwt/status` | JWT 认证状态 | -| GET | `/api/security/brute-force/status` | 暴力破解防御状态 | -| GET | `/api/security/anti-bot/status` | 反机器人状态 | -| GET | `/api/security/reverse-shell/status` | 反向 Shell 检测状态 | -| GET | `/api/security/arp-spoof/status` | ARP 欺骗检测状态 | -| GET | `/api/security/dns-tunnel/status` | DNS 隧道状态 | -| GET | `/api/security/exploit-signature/status` | 漏洞签名状态 | -| GET | `/api/security/ssrf/status` | SSRF 防护状态 | -| GET | `/api/security/xxe/status` | XXE 防护状态 | -| GET | `/api/security/csp/status` | CSP 状态 | -| GET | `/api/security/database-firewall/status` | 数据库防火墙状态 | -| GET | `/api/security/dlp/status` | 数据防泄漏状态 | -| GET | `/api/security/memory-protection/status` | 内存保护状态 | -| GET | `/api/security/process-injection/status` | 进程注入检测状态 | -| GET | `/api/security/secure-delete/status` | 安全删除状态 | -| GET | `/api/security/forensics/status` | 取证状态 | -| GET | `/api/security/incident-response/status` | 事件响应状态 | -| GET | `/api/security/threat-hunting/status` | 威胁狩猎状态 | -| GET | `/api/security/compliance/status` | 合规扫描状态 | - -### 6.4 Minecraft 专属防御 - -| 方法 | 路径 | 说明 | -|------|------|------| -| GET | `/api/security/anti-grief/status` | 反破坏检测状态 | -| GET | `/api/security/anti-xray/status` | 反 X-ray 状态 | -| GET | `/api/security/anti-fly/status` | 反飞行外挂状态 | -| GET | `/api/security/anti-dupe/status` | 反物品复制状态 | -| GET | `/api/security/crash-exploit/status` | 崩溃漏洞防护状态 | -| GET | `/api/security/lag-machine/status` | 反卡服机状态 | - -### 6.5 运维操作 - -| 方法 | 路径 | 说明 | -|------|------|------| -| POST | `/api/player/kick` | 踢出玩家 | -| POST | `/api/player/ban` | 封禁玩家 | -| POST | `/api/player/unban` | 解封玩家 | -| GET | `/api/player/list` | 在线玩家列表 | -| POST | `/api/world/backup` | 触发世界备份 | -| GET | `/api/world/backup/list` | 备份列表 | -| POST | `/api/world/restore` | 恢复世界备份 | -| GET | `/api/profile` | 性能分析数据 | -| POST | `/api/security/report/generate` | 生成安全报告 | - -### 6.6 返回格式 - -```json -{ - "success": true, - "data": { ... }, - "timestamp": "2026-05-10T22:00:00+08:00" +```java +if (!config.getSecurity().getSuperEvolution().isAntiKillAura()) { + return DetectionResult.clean(); // 模块已禁用,跳过检测 } ``` --- -## 7. CLI 命令系统 +## 添加新反作弊模块 -### 7.1 架构 +### 完整步骤 -基于 Spring Shell 3.1.3,入口类 `AITerminal` (`@ShellComponent`)。支持 `@ShellMethod` 注解自动注册。 +**第一步:确认反作弊 Hack 类型** -### 7.2 命令分类 +查阅 Meteor Client 的 hack 分类(Combat/Movement/World/Player/Misc/Render),确定你要对抗的 hack 名称和类型。 -| 类别 | 命令数 | 说明 | -|------|--------|------| -| `all` | ~35 | 全部命令列表(默认) | -| `ai` | 6 | AI 分析与策略指令 | -| `status` | 5 | 系统状态查询 | -| `defense` | 8 | 防御模式控制 | -| `security` | 6 | 安全模块管理 | -| `monitor` | 4 | 监控数据查询 | -| `player` | 5 | 玩家管理 | -| `world` | 3 | 世界/备份管理 | -| `admin` | 6 | 管理员运维操作 | +**第二步:创建 Service 类** -### 7.3 使用示例 - -```bash -# 启动终端 -java -jar AluerServerGuard-V4.0.jar - -# 在终端内 -help # 显示完整命令参考 -help ai # AI 相关命令 -help security # 安全相关命令 -help all # 全部命令(含 API 端点列表) - -# 自然语言交互 -分析当前服务器安全状态 -查看最近攻击报告 -``` - ---- - -## 8. 测试策略 - -### 8.1 测试框架 - -- JUnit 5 (Jupiter) -- Plain POJO 测试(不加载 Spring 上下文) -- 不依赖 Mockito - -### 8.2 测试文件清单 - -| 测试类 | 用例数 | 覆盖范围 | -|--------|--------|----------| -| `MinecraftSecurityTest` | 21 | 核心安全模块 | -| `SuperEvolutionSecurityTest` | 52 | v3.1/v3.2 扩展模块 | -| `V33SecurityTest` | 29 | v3.3 新模块 (6 个服务) | -| `WebApplicationFirewallTest` | 2 | WAF 引擎 | -| `NetworkThreatFusionServiceTest` | 2 | 威胁融合 | -| `SecurityBaselineHardeningServiceTest` | 1 | 安全基线 | -| `AluerKernelEngineTest` | 2 | 内核引擎 | -| `AluerKernelTaskBusTest` | 1 | 任务总线 | -| `AluerSelfHealingOrchestratorTest` | 1 | 自愈编排 | -| `AluerEngineHandshakeServiceTest` | 1 | 引擎握手 | -| `AluerMirageShieldServiceTest` | 1 | Mirage 盾 | -| `RemoteSshGatewayServiceTest` | 1 | SSH 网关 | -| **总计** | **114** | | - -### 8.3 运行测试 - -```bash -./apache-maven-3.9.6/bin/mvn test -``` - -### 8.4 测试模式 - -所有安全服务使用双构造函数,测试中直接 `new ServiceName()` 实例化,无需 Spring 容器。涉及文件 I/O 的测试使用 `/tmp/` 路径配合不存在的文件,避免磁盘污染。 - ---- - -## 9. 构建与部署 - -### 9.1 环境要求 - -| 项目 | 最低要求 | -|------|----------| -| JDK | 17+ | -| 构建工具 | 内置 Maven 3.9.6 (无需系统安装) | -| 操作系统 | Linux (推荐 Ubuntu 22.04+) | -| 内存 | 建议 2GB+ 可用 | -| 磁盘 | 建议 10GB+ 可用 | - -### 9.2 构建命令 - -```bash -# 编译 + 运行全部测试 -./apache-maven-3.9.6/bin/mvn test - -# 构建 fat JAR(跳过测试) -./apache-maven-3.9.6/bin/mvn package -DskipTests - -# 产物位置 -# target/serverguard.jar (Spring Boot 可执行 fat JAR) -``` - -### 9.3 部署 - -```bash -# 复制到目标服务器 -scp release/V4.0/AluerServerGuard-V4.0.jar user@server:/opt/aluer/ - -# 启动(前台测试) -java -jar /opt/aluer/AluerServerGuard-V4.0.jar - -# 启动(后台生产) -nohup java -jar /opt/aluer/AluerServerGuard-V4.0.jar > /var/log/aluer.log 2>&1 & - -# 或使用 systemd(配置见 systemd/ 目录) -sudo systemctl enable aluer -sudo systemctl start aluer -``` - -### 9.4 版本发布 - -发布产物存放于 `release/V4.0/` 目录: - -| 文件 | 说明 | -|------|------| -| `AluerServerGuard-V4.0.jar` | Spring Boot fat JAR (~29MB) | - ---- - -## 10. 安全机制层次 - -系统实现四层纵深防御体系: - -``` -第一层 — 边界防御 - GeoBlock, ConnectionThrottle, IPReputation, DDoS Protection - Cloudflare Integration, Port Scan Detection - -第二层 — 网络与协议 - Firewall, IDS/IPS, Deep Packet Inspection, Protocol Analysis - DNS Tunnel Detection, ARP Spoof Detection, Reverse Shell Detection - DNSSEC, SSL/TLS Monitoring - -第三层 — 应用与数据 - WAF, JWT Auth, Brute Force Protection, Anti-Bot - CSP, XXE Protection, SSRF Protection - SQL Firewall, DLP, Encryption Service - Session Management, API Rate Limit - -第四层 — 主机与运营 - Memory Protection, Process Injection Detection - File Integrity Monitoring, Secure Delete, Forensics - Anti-Cheat (Xray/Fly/Dupe/Grief) - Crash Exploit, Lag Machine, Skin Spoof - Plugin Verification, Backup Integrity - Compliance Scanner, Threat Hunting, Incident Response -``` - ---- - -## 11. 扩展开发指南 - -### 11.1 新增安全模块流程 - -**步骤 1** — 创建服务类 (`src/main/java/com/aluer/security/NewDetectionService.java`) +在 `src/main/java/com/aluer/security/` 下创建新类,遵循命名规范 `Anti{Xxx}Service.java`: ```java package com.aluer.security; import com.aluer.config.ServerGuardConfig; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; + import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +/** + * {Hack名称}检测服务 — V5.X 反作弊模块 + * + * 检测原理: + * 1. {原理1的详细说明} + * 2. {原理2的详细说明} + * + * 配置开关:serverguard.security.super-evolution.anti-{xxx} + */ @Service -public class NewDetectionService { +public class AntiNewHackService { private final ServerGuardConfig config; - private final AtomicLong detectionCount = new AtomicLong(0); - private final Map> history = new ConcurrentHashMap<>(); - public NewDetectionService() { this(new ServerGuardConfig()); } + /** 追踪每个玩家的行为数据 */ + private final Map> playerHistory = new ConcurrentHashMap<>(); - @Autowired - public NewDetectionService(ServerGuardConfig config) { this.config = config; } + private final AtomicLong totalChecks = new AtomicLong(0); + private final AtomicLong flaggedCount = new AtomicLong(0); - public DetectionResult detect(String input, String source) { - if (!config.getSecurity().getSuperEvolution().isNewDetection()) { + // 常量定义 + private static final int ANALYSIS_WINDOW_MS = 3000; + private static final double FLAG_THRESHOLD = 0.85; + + /** 无参构造函数(测试用) */ + public AntiNewHackService() { + this.config = new ServerGuardConfig(); + } + + /** @Autowired 构造函数(生产用) */ + public AntiNewHackService(ServerGuardConfig config) { + this.config = config; + } + + /** + * 分析玩家行为,检测是否存在 {hack名称} 作弊 + * + * @param playerName 玩家名称 + * @param eventData 事件数据(根据 hack 类型确定参数) + * @return 检测结果(CLEAN/FLAGGED/BLOCKED) + */ + public DetectionResult analyze(String playerName, EventData eventData) { + // 1. 检查模块是否启用 + if (!config.getSecurity().getSuperEvolution().isAntiNewHack()) { return DetectionResult.clean(); } - // 检测逻辑... + + totalChecks.incrementAndGet(); + + // 2. 更新玩家行为历史 + List history = playerHistory.computeIfAbsent( + playerName, k -> Collections.synchronizedList(new ArrayList<>()) + ); + history.add(new BehaviorRecord(eventData, System.currentTimeMillis())); + + // 3. 清理过期记录(超出分析窗口) + long cutoff = System.currentTimeMillis() - ANALYSIS_WINDOW_MS; + history.removeIf(r -> r.timestamp < cutoff); + + // 4. 分析行为模式 + double anomalyScore = computeAnomalyScore(history); + + // 5. 返回结果 + if (anomalyScore > FLAG_THRESHOLD) { + flaggedCount.incrementAndGet(); + return DetectionResult.flagged( + String.format("NewHack detected: anomaly score %.2f", anomalyScore), + anomalyScore + ); + } + return DetectionResult.clean(); } - public Map getStatus() { - Map s = new LinkedHashMap<>(); - s.put("totalDetections", detectionCount.get()); - return s; + private double computeAnomalyScore(List history) { + // 实现具体的异常检测算法 + // ... + return 0.0; } - public static class DetectionResult { - private final boolean flagged; - private final List reasons; - private DetectionResult(boolean f, List r) { this.flagged = f; this.reasons = r; } - public static DetectionResult clean() { return new DetectionResult(false, List.of()); } - public static DetectionResult flagged(List r) { return new DetectionResult(true, r); } - public boolean isFlagged() { return flagged; } - public List getReasons() { return reasons; } - } - - private static class DetectionEvent { + /** 行为记录内部类 */ + private static class BehaviorRecord { + final EventData data; final long timestamp; - final String source; - final String input; - DetectionEvent(long t, String s, String i) {} + + BehaviorRecord(EventData data, long timestamp) { + this.data = data; + this.timestamp = timestamp; + } + } + + /** 检测结果(静态工厂) */ + public static class DetectionResult { + public enum Status { CLEAN, BLOCKED, FLAGGED } + + private final Status status; + private final String reason; + private final double confidence; + + private DetectionResult(Status status, String reason, double confidence) { + this.status = status; + this.reason = reason; + this.confidence = confidence; + } + + public static DetectionResult clean() { + return new DetectionResult(Status.CLEAN, null, 0.0); + } + + public static DetectionResult blocked(String reason, double confidence) { + return new DetectionResult(Status.BLOCKED, reason, confidence); + } + + public static DetectionResult flagged(String reason, double confidence) { + return new DetectionResult(Status.FLAGGED, reason, confidence); + } + + public Status getStatus() { return status; } + public String getReason() { return reason; } + public double getConfidence() { return confidence; } + public boolean isClean() { return status == Status.CLEAN; } + public boolean isBlocked() { return status == Status.BLOCKED; } + public boolean isFlagged() { return status == Status.FLAGGED; } } } ``` -**步骤 2** — 添加配置开关 (`ServerGuardConfig.SuperEvolutionConfig` 中添加 `boolean` 字段) +**第三步:添加告警类型** -**步骤 3** — 添加 YAML 配置 (`application.yml` 中添加带中文注释的开关行) +在 `AlertType.java` 中新增枚举值: -**步骤 4** — 注册 API 端点 (`DashboardController` 中添加 `@GetMapping` 方法) +```java +// 在对应分类区域添加 +SECURITY_NEW_HACK("NewHack", "Description of this hack detection"), +``` -**步骤 5** — 编写测试 (至少 3 个用例:正常/异常/状态) +**第四步:添加配置开关** -**步骤 6** — 更新文档 +在 `ServerGuardConfig.SuperEvolutionConfig` 中新增: -### 11.2 代码规范 +```java +// 属性声明 +private boolean antiNewHack = true; -- 使用 `LinkedHashMap` 保持状态 Map 的插入顺序 -- 并发场景使用 `ConcurrentHashMap` + `AtomicLong` -- 结果类使用内部静态类,构造函数私有,提供静态工厂方法 -- 不引入 Lombok 以外的额外依赖 -- 日志使用 Slf4j,级别:WARN(关键事件)、INFO(状态变更)、DEBUG(详细追踪) -- 禁止在安全服务中执行阻塞 I/O 操作;所有文件操作使用异步调度器 +// Getter +public boolean isAntiNewHack() { return antiNewHack; } + +// Setter +public void setAntiNewHack(boolean antiNewHack) { this.antiNewHack = antiNewHack; } +``` + +**第五步:添加 application.yml 配置** + +```yaml +# 在 super-evolution 节中添加 +anti-new-hack: true # 新Hack检测说明 +``` + +**第六步:编写单元测试** + +在 `src/test/java/com/aluer/security/` 下创建测试类: + +```java +package com.aluer.security; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class AntiNewHackServiceTest { + + private final AntiNewHackService service = new AntiNewHackService(); + + @Test + void testCleanBehavior() { + // 正常玩家行为应该返回 CLEAN + // ... + } + + @Test + void testFlaggedBehavior() { + // 异常行为应该返回 FLAGGED + // ... + } + + @Test + void testModuleDisabled() { + // 模块关闭时应返回 CLEAN + // ... + } +} +``` + +**第七步:全量测试** + +```bash +./apache-maven-3.9.6/bin/mvn test +``` + +确保所有现有测试和新测试全部通过。 --- -
-

Aluer ServerGuard V4.0

-

为 Minecraft 服务器安全构建的专业防护系统

-

Apache 2.0 License © 2026

-
+## 事件监听器模式 + +### 监听器基类结构 + +所有 Bukkit 事件监听器位于 `com.aluer.plugin.listener` 包下,每个监听器负责一类事件: + +```java +package com.aluer.plugin.listener; + +import com.aluer.plugin.bridge.DataBridge; +import org.bukkit.event.Listener; + +/** + * {事件类别}监听器 — 拦截 Bukkit 事件并转发至 ServerGuard 引擎 + */ +public class XxxEventListener implements Listener { + + private final DataBridge dataBridge; + + public XxxEventListener(DataBridge dataBridge) { + this.dataBridge = dataBridge; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onXxxEvent(XxxEvent event) { + // 1. 提取事件数据 + // 2. 通过 DataBridge 转换为 AgentMessage + // 3. 通过 WebSocket 发送至 ServerGuard + dataBridge.sendEvent("EVENT_TYPE", eventData); + } +} +``` + +### 九大监听器及其监听事件 + +| 监听器 | 主要监听事件 | 数据类型 | +|--------|------------|---------| +| BlockEventListener | BlockBreakEvent, BlockPlaceEvent | 方块坐标、类型、玩家、工具 | +| ChatEventListener | AsyncPlayerChatEvent | 消息内容、发送时间 | +| CombatEventListener | EntityDamageByEntityEvent, PlayerDeathEvent | 攻击者、目标、伤害量、武器 | +| CommandEventListener | PlayerCommandPreprocessEvent | 命令文本、执行时间 | +| EntityEventListener | EntitySpawnEvent, EntityDeathEvent | 实体类型、坐标、原因 | +| InventoryEventListener | InventoryClickEvent, InventoryOpenEvent | 槽位、物品类型、容器位置 | +| PacketEventListener | PacketEvent (ProtocolLib) | 原始数据包内容 | +| PlayerEventListener | PlayerJoinEvent, PlayerQuitEvent, PlayerMoveEvent | 玩家信息、坐标、移动向量 | +| WorldEventListener | ChunkLoadEvent, ChunkUnloadEvent | 区块坐标、加载原因 | + +### DataBridge 数据转换 + +`DataBridge` 负责将 Bukkit 事件数据转换为 AgentMessage JSON 格式: + +```java +public class DataBridge { + private final AgentWebSocketClient wsClient; + + public void sendEvent(String eventType, JsonObject eventData) { + JsonObject payload = new JsonObject(); + payload.addProperty("eventType", eventType); + // 添加通用字段 + payload.add("data", eventData); + + String message = AgentMessage.buildMessage( + AgentMessage.TYPE_EVENT, + agentId, + payload + ); + wsClient.send(message); + } +} +``` + +--- + +## Agent 通信协议详解 + +### 协议设计 + +通信基于 WebSocket (RFC 6455),所有消息为单行 JSON 文本帧。 + +### 消息类型枚举 + +定义在 `AgentMessage.java` 中: + +**Agent → Server:** +| 常量 | 值 | 说明 | +|------|-----|------| +| TYPE_EVENT | "EVENT" | Bukkit 事件上报 | +| TYPE_METRICS | "METRICS" | 服务器性能指标 | +| TYPE_ALERT | "ALERT" | 安全告警上报 | +| TYPE_HEARTBEAT | "HEARTBEAT" | 心跳保活(间隔由Kernel配置) | +| TYPE_HANDSHAKE | "HANDSHAKE" | 初始连接握手 | +| TYPE_COMMAND_RESULT | "COMMAND_RESULT" | 命令执行结果回执 | + +**Server → Agent:** +| 常量 | 值 | 说明 | +|------|-----|------| +| TYPE_COMMAND | "COMMAND" | 防御指令下发 | +| TYPE_CONFIG | "CONFIG" | 动态配置更新 | +| TYPE_SHUTDOWN | "SHUTDOWN" | 连接关闭通知 | + +### 命令类型 + +| 常量 | 值 | 对应 Bukkit 操作 | +|------|-----|-----------------| +| CMD_BAN_IP | "BAN_IP" | Bukkit.banIP() | +| CMD_BAN_PLAYER | "BAN_PLAYER" | Bukkit.getBanList().addBan() | +| CMD_KICK | "KICK" | Player.kickPlayer() | +| CMD_CLEAR_LAG | "CLEAR_LAG" | World.getEntities().clear() | +| CMD_SET_SPAWN_RATE | "SET_SPAWN_RATE" | 调整 spawn-limits | +| CMD_ENABLE_WHITELIST | "ENABLE_WHITELIST" | Bukkit.setWhitelist(true) | +| CMD_DISABLE_WHITELIST | "DISABLE_WHITELIST" | Bukkit.setWhitelist(false) | +| CMD_BROADCAST | "BROADCAST" | Bukkit.broadcastMessage() | +| CMD_SAVE_ALL | "SAVE_ALL" | Bukkit.savePlayers() + World.save() | +| CMD_EXECUTE | "EXECUTE" | Bukkit.dispatchCommand() | + +### 事件类型 + +| 常量 | 值 | 关联 Bukkit 事件 | +|------|-----|-----------------| +| EVENT_PLAYER_JOIN | "PLAYER_JOIN" | PlayerJoinEvent | +| EVENT_PLAYER_QUIT | "PLAYER_QUIT" | PlayerQuitEvent | +| EVENT_PLAYER_MOVE | "PLAYER_MOVE" | PlayerMoveEvent | +| EVENT_PLAYER_TELEPORT | "PLAYER_TELEPORT" | PlayerTeleportEvent | +| EVENT_PLAYER_CHAT | "PLAYER_CHAT" | AsyncPlayerChatEvent | +| EVENT_PLAYER_COMMAND | "PLAYER_COMMAND" | PlayerCommandPreprocessEvent | +| EVENT_PLAYER_DAMAGE | "PLAYER_DAMAGE" | EntityDamageEvent | +| EVENT_COMBAT_ATTACK | "COMBAT_ATTACK" | EntityDamageByEntityEvent | +| EVENT_COMBAT_DEATH | "COMBAT_DEATH" | PlayerDeathEvent | +| EVENT_BLOCK_BREAK | "BLOCK_BREAK" | BlockBreakEvent | +| EVENT_BLOCK_PLACE | "BLOCK_PLACE" | BlockPlaceEvent | +| EVENT_INVENTORY_CLICK | "INVENTORY_CLICK" | InventoryClickEvent | +| EVENT_ENTITY_SPAWN | "ENTITY_SPAWN" | EntitySpawnEvent | +| EVENT_CHUNK_LOAD | "CHUNK_LOAD" | ChunkLoadEvent | + +### 消息格式规范 + +```java +// Agent → Server: 构建消息 +public static String buildMessage(String type, String agentId, JsonObject payload) { + JsonObject msg = new JsonObject(); + msg.addProperty("type", type); + msg.addProperty("agentId", agentId); + msg.addProperty("timestamp", Instant.now().toEpochMilli()); + msg.add("payload", payload); + return gson.toJson(msg); +} + +// Server → Agent: 构建命令 +public static String buildCommand(String commandType, String target, String reason) { + JsonObject payload = new JsonObject(); + payload.addProperty("command", commandType); + payload.addProperty("target", target != null ? target : ""); + payload.addProperty("reason", reason != null ? reason : ""); + + JsonObject msg = new JsonObject(); + msg.addProperty("type", TYPE_COMMAND); + msg.addProperty("requestId", UUID.randomUUID().toString()); + msg.addProperty("timestamp", Instant.now().toEpochMilli()); + msg.add("payload", payload); + return gson.toJson(msg); +} + +// 解析工具方法 +public static String getType(String message) { /* 解析 type 字段 */ } +public static JsonObject getPayload(String message) { /* 解析 payload 对象 */ } +public static String getAgentId(String message) { /* 解析 agentId 字段 */ } +``` + +--- + +## 配置系统 + +### 配置层次结构 + +``` +application.yml + └── serverguard.* # 所有配置的前缀 + ├── mode # 运行模式:plugin | external + ├── minecraft.* # Minecraft 进程管理 + ├── monitor.* # 监控阈值 + ├── alert.* # 告警配置 + │ └── email.* # 邮件配置 + ├── ai.* # AI/ML 配置 + │ └── deepseek.* # DeepSeek 集成 + │ └── auto-execute.* # 自动执行 + ├── security.* # 安全配置 + │ ├── minecraft-defense.* # 协议层防御 + │ ├── ddos-defense.* # DDoS 防御 + │ ├── anti-intrusion.* # 入侵检测 + │ │ └── file-integrity.* # 文件完整性 + │ ├── host-enforcement.* # 主机强制 + │ ├── cloud-edge.* # 云端边缘 + │ ├── threat-feeds.* # 威胁情报 + │ ├── orchestration.* # 编排 + │ ├── automation.* # 自动化 + │ ├── autonomy.* # 自主决策 + │ ├── shield.* # 护盾 + │ ├── kernel.* # 内核 + │ ├── task-bus.* # 任务总线 + │ ├── self-healing.* # 自愈 + │ └── super-evolution.* # 模块开关(70+个) + ├── dashboard.* # Web 控制台 + │ └── ssh-gateway.* # SSH 网关 + ├── announcement.* # 公告 + ├── afk.* # AFK 管理 + ├── chat-filter.* # 聊天过滤 + ├── backup.* # 备份 + └── schedule.* # 定时任务 +``` + +### 配置类映射关系 + +`ServerGuardConfig` 使用 `@ConfigurationProperties(prefix = "serverguard")` 注解,Spring Boot 自动将 YAML 配置绑定到对应的嵌套静态内部类。 + +命名转换规则: +- YAML 中 `kebab-case`(如 `tps-threshold`) +- Java 中 `camelCase`(如 `tpsThreshold`) +- Spring Boot 自动完成转换 + +### 环境变量覆盖 + +配置值可以使用 `${ENV_VAR:default}` 语法通过环境变量覆盖,示例如下: + +```yaml +serverguard: + mode: ${SERVERGUARD_MODE:external} + ai: + deepseek: + api-key: ${DEEPSEEK_API_KEY:} + model: ${DEEPSEEK_MODEL:deepseek-chat} + alert: + email: + username: ${ALUER_ALERT_SMTP_USERNAME:} + password: ${ALUER_ALERT_SMTP_PASSWORD:} +``` + +--- + +## ML/AI 集成 + +### 四大 ML 模块 + +| 模块 | 功能 | 算法 | +|------|------|------| +| BehavioralProfilingEngine | 基于统计特征建立玩家行为基线,检测偏离 | Isolation Forest, Statistical Profiling | +| CombatPatternRecognizer | 识别异常战斗序列(多目标切换、异常连击模式) | Pattern Matching, Sequence Analysis | +| MovementPatternAnalyzer | 分析移动轨迹异常(路径熵值、加速度模式) | Trajectory Analysis, Entropy Calculation | +| ThreatScoreAggregator | 融合多维度检测结果,生成统一威胁评分 | Weighted Aggregation, Escalation Logic | + +### AI 配置参数 + +```yaml +ai: + enabled: true + use-isolation-forest: true # 启用隔离森林 + use-prediction: true # 启用时间序列预测 + sliding-window-size: 100 # 滑动窗口数据点数 + anomaly-threshold: 0.7 # 异常判定阈值 (0.0-1.0) + prediction-horizon-minutes: 60 # 预测未来时间范围 +``` + +### DeepSeek 集成 + +```yaml +ai: + deepseek: + enabled: true + api-key: ${DEEPSEEK_API_KEY:} + base-url: https://api.deepseek.com + model: deepseek-chat + max-tokens: 1000 + temperature: 0.35 # 低温度获得稳定分析 + auto-analyze-alerts: true # 自动分析所有告警 + analysis-interval-seconds: 45 # 分析间隔 + auto-execute: + enabled: true + ban-ip: true + kill-entity: true + clear-lag: true + set-spawn-rate: true + kick-player: true + whitelist: true + min-confidence: 88 # 低于此置信度不自动执行 +``` + +--- + +## 测试规范 + +### 测试原则 + +1. **打靶试验** — 测试必须模拟真实 Minecraft 服务器环境,不允许使用假数据 +2. **生产对齐** — 测试数据和行为必须与实际生产环境对齐 +3. **全量验证** — 修改代码前后必须跑全量 278 项测试,一个不能挂 +4. **双构造函数模式** — 每个 Service 必须提供无参构造函数用于测试 + +### 测试类命名规范 + +``` +src/test/java/com/aluer/ +├── security/ +│ ├── AntiKillAuraServiceTest.java +│ ├── AntiReachServiceTest.java +│ └── ... +├── ml/ +│ ├── BehavioralProfilingEngineTest.java +│ └── ... +└── plugin/ + └── ... +``` + +### 测试方法命名 + +```java +@Test +void testCleanBehavior() { } // 正常行为 → CLEAN +@Test +void testFlaggedBehavior() { } // 可疑行为 → FLAGGED +@Test +void testBlockedBehavior() { } // 明确作弊 → BLOCKED +@Test +void testModuleDisabled() { } // 模块关闭 → CLEAN +@Test +void testEdgeCase() { } // 边界条件 +@Test +void testPerformance() { } // 性能测试 +``` + +### 运行测试 + +```bash +# 全量测试 +./apache-maven-3.9.6/bin/mvn test + +# 运行特定测试类 +./apache-maven-3.9.6/bin/mvn test -Dtest=AntiKillAuraServiceTest + +# 运行特定测试方法 +./apache-maven-3.9.6/bin/mvn test -Dtest=AntiKillAuraServiceTest#testFlaggedBehavior +``` + +--- + +## 代码风格指南 + +### 命名规范 + +| 元素 | 规范 | 示例 | +|------|------|------| +| 包名 | 全小写 | `com.aluer.security` | +| 类名 | PascalCase | `AntiKillAuraService` | +| 方法名 | camelCase | `analyzePlayerBehavior()` | +| 常量 | UPPER_SNAKE_CASE | `MAX_ATTACK_DISTANCE` | +| 配置属性 | camelCase (Java) / kebab-case (YAML) | `tpsThreshold` / `tps-threshold` | +| 枚举值 | UPPER_SNAKE_CASE | `SECURITY_KILL_AURA` | + +### 注释规范 + +- **类级别**:必须有 JavaDoc 注释,说明模块功能、检测原理、配置开关 +- **方法级别**:必须有 JavaDoc 注释,说明参数、返回值、算法思路 +- **关键逻辑**:行内注释解释 WHY 而非 WHAT +- **语言**:使用中文注释 + +```java +/** + * 杀戮光环(KillAura)检测服务 — V4.0 反作弊扩展模块 + * + * 检测原理: + * 1. 攻击目标切换频率检测 — 追踪每个玩家的攻击目标列表,如果在3秒窗口内切换超过3个不同目标 + * 2. 攻击角度一致性检测 — 连续攻击的角度偏差小于5度时,表明存在自动瞄准(Aimbot) + * + * 配置开关:serverguard.security.super-evolution.anti-kill-aura + */ +@Service +public class AntiKillAuraService { + // ... +} +``` + +### 代码组织 + +```java +// 1. Package 声明 +// 2. Import 语句(按字母排序,静态导入在后) +// 3. 类 JavaDoc +// 4. @Service 或其他注解 +// 5. 类声明 +// 6. 常量字段 +// 7. 配置注入字段 +// 8. 数据追踪字段(ConcurrentHashMap, AtomicLong) +// 9. 构造函数(无参 + @Autowired) +// 10. 公共分析方法 +// 11. 私有辅助方法 +// 12. 内部类(BehaviorRecord, DetectionResult) +``` + +### Git 提交规范 + +- 使用中文 commit message +- 格式:`{类型}: {简短描述}` +- 类型:新增、修复、重构、文档、测试、优化 +- 频繁提交,每个有意义的改动单独提交 + +示例: +``` +新增: AntiAutoCrystal 末影水晶自动化检测模块 +修复: Reach 检测误判穿墙攻击时的距离计算错误 +重构: 统一所有安全模块的 DetectionResult 返回类型 +``` + +--- + +## 构建系统 + +### Maven 配置 + +项目使用 Apache Maven 3.9.6(bundled),配置文件 `pom.xml`。 + +### 关键依赖 + +```xml + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-websocket + + + org.springframework.boot + spring-boot-starter-mail + + + + + org.springframework.shell + spring-shell-starter + 3.1.3 + + + + + io.papermc.paper + paper-api + 1.21.1-R0.1-SNAPSHOT + provided + + + + + com.github.haifengl + smile-core + 2.6.0 + + + org.apache.commons + commons-math3 + 3.6.1 + + + + + org.yaml + snakeyaml + 2.2 + + + + + com.google.code.gson + gson + + +``` + +### 构建命令速查 + +```bash +# 编译(不运行测试) +./apache-maven-3.9.6/bin/mvn compile + +# 编译 + 运行全量测试 +./apache-maven-3.9.6/bin/mvn test + +# 打包(跳过测试) +./apache-maven-3.9.6/bin/mvn package -DskipTests + +# 打包 + 运行测试 +./apache-maven-3.9.6/bin/mvn package + +# 清理构建产物 +./apache-maven-3.9.6/bin/mvn clean + +# 清理 + 完整重新构建 +./apache-maven-3.9.6/bin/mvn clean package +``` + +### 构建产物 + +``` +target/ +├── serverguard-4.0.0.jar # 可执行 JAR(Spring Boot Fat JAR) +├── classes/ # 编译后的 .class 文件 +├── test-classes/ # 测试编译产物 +├── generated-sources/ # 注解处理器生成 +└── surefire-reports/ # 测试报告 +``` + +### 部署产物说明 + +- `serverguard-4.0.0.jar` 是 Spring Boot 可执行 JAR,包含所有依赖 +- 同时作为 Paper 插件使用(复制到 `plugins/` 目录) +- Plugin 模式下,AluerPlugin 作为 Paper 插件启动,但不启动嵌入的 Spring Boot(由外部引擎独立运行) diff --git a/docs/PROJECT_SUMMARY.md b/docs/PROJECT_SUMMARY.md index 7fef577..0aa02ae 100644 --- a/docs/PROJECT_SUMMARY.md +++ b/docs/PROJECT_SUMMARY.md @@ -1,239 +1,425 @@ -# AluerIII 服务器安全防护系统 - 详细项目概括与功能拆解 +# Aluer ServerGuard V5.0 -- 项目总览与模块拆解 -AluerIII 是一个专为 Minecraft (PaperMC) 服务器设计的高级安全防护与自动化运维系统。它集成了 **AI 驱动威胁感知**、**多层网络安全防御**、**实时监控预警** 与 **自动化管理** 功能。本项目采用 Java 与 Spring Boot 框架构建,具有高度模块化和可扩展的插件式架构。 - -以下是项目中所有核心模块、包路径及具体类的极其详细的功能拆解: +> 本文档提供 Aluer ServerGuard 项目的宏观总览,包括完整模块清单、技术栈、性能特征和安全覆盖矩阵。 --- -## 1. AI 智能防御与分析模块 (`com.aluer.ai`) -该模块是系统的“大脑”,利用机器学习算法和大型语言模型(如 DeepSeek)进行实时威胁感知、趋势预测与智能决策。 +## 项目标识 -- **`AIAutonomousService`** (自主防御核心) - - 通过正则匹配和流量模式识别潜在威胁(如 SQL 注入、DDoS 攻击)。 - - 在检测到威胁时,自动执行防御动作(如动态封禁恶意 IP、启用限流)。 -- **`AIStrategyEngine`** (智能策略引擎) - - 根据检测到的威胁严重程度(Severity),动态匹配并下发最佳防御策略(例如:“暴力破解”对应“临时封禁+启用验证码”)。 -- **`DeepSeekClient`** (AI 接口集成) - - 将服务器的异常指标、告警日志发送至 DeepSeek AI 进行深度分析。 - - 自动生成易于理解的健康报告、根本原因分析(RCA)及修复建议。 -- **`AnomalyDetector`** (异常检测器) - - 使用孤立森林(Isolation Forest)等算法检测服务器性能指标(如 CPU、内存突增)中的非典型波动。 -- **`AttackDetector`** (协同攻击检测) - - 关联分析网络连接行为与日志,识别分布式的协同攻击(如慢速连接攻击、僵尸网络扫描)。 -- **`TimeSeriesPredictor`** (时间序列预测) - - 基于历史运行数据预测未来 TPS 走势,提前预警可能的服务器卡顿或内存溢出崩溃。 -- **`AdaptiveThreshold`** (自适应阈值控制器) - - 学习服务器的历史负载模式,动态调整各项监控告警的触发阈值,有效降低误报率。 +| 属性 | 值 | +|------|-----| +| 项目名称 | Aluer ServerGuard | +| 当前版本 | V5.0 (V5.3 子版本) | +| 构建工具 | Apache Maven 3.9.6 (bundled) | +| 代码语言 | Java 21 | +| 应用框架 | Spring Boot 3.2.0 | +| 目标平台 | Minecraft PaperMC 1.21.1 | +| 源码文件数 | ~170 个 Java 文件 | +| 安全模块数 | 135 个 | +| 告警类型 | 75 种 | --- -## 2. 核心安全防护系统 (`com.aluer.security`) -系统最庞大的子模块,提供了从网络层(L3/L4)到应用层(L7)的全方位纵深防御体系。 +## 模块统计总览 -- **`WebApplicationFirewall (WAF)`** (Web 应用防火墙) - - 针对 Web 控制面板和 API 接口,提供 SQLi、XSS、路径遍历等常见 Web 攻击过滤,并维护客户端请求信誉度。 -- **`DDoSProtectionService`** (DDoS 防护引擎) - - 专防分布式拒绝服务攻击,支持识别 SYN Flood、HTTP Flood、UDP 放大攻击及 ICMP Flood,并执行自动 IP 封禁与流量清洗。 -- **`IntrusionDetectionService (IDS)` / `IntrusionPreventionSystem (IPS)`** (入侵检测与防御) - - 实时扫描服务器内的恶意行为和越权访问,自动阻断非法连接。 -- **`SIEMService`** (安全信息与事件管理) - - 关联不同来源的碎片化事件(如“多次登录失败”+“异常权限变更”),识别出复杂的横向移动或权限提升攻击序列。 -- **`IPReputationService` / `GeoIPService`** (IP 信誉与地理位置) - - 基于全局 IP 黑名单及地理位置库进行流量过滤(如一键屏蔽特定国家或高风险云服务商的流量)。 -- **`HoneypotService`** (蜜罐诱捕系统) - - 通过暴露诱饵端口或伪造的脆弱接口,吸引并捕获扫描者和攻击者,收集威胁情报。 -- **`ZeroTrustArchitectureService`** (零信任架构) - - 实施严格的持续身份验证与最小权限校验,确保内部和外部调用的绝对安全。 -- **`AdvancedMalwareDetectionService`** (高级恶意软件扫描) - - 定期扫描服务器内的可疑文件(如被植入后门的插件)及玩家上传的内容。 -- **`FirewallService`** / **`NetworkMonitorService`** (防火墙与网络监控) - - 管理底层系统防火墙规则(iptables/ufw),监控进出站流量异常。 +| 类别 | 模块数量 | 描述 | +|------|---------|------| +| 反作弊 -- 战斗类 | 15 | KillAura, Reach, Speed, Criticals, AutoCrystal 等 | +| 反作弊 -- 移动类 | 18 | Fly, Jesus, NoFall, Timer, Phase, Spider 等 | +| 反作弊 -- 世界/玩家/杂物类 | 19 | Nuker, AutoMine, Xray, Baritone, Dupe 等 | +| 服务器漏洞防护 | 12 | SignExploit, BookBan, CrashExploit, LagMachine 等 | +| 聊天与社交安全 | 5 | ChatFlood, Advertisement, Phishing, CommandAbuse | +| 网络安全 | 13 | DDoS, ProtocolViolation, BotFingerprint, VPN 等 | +| 主机与访问控制 | 6 | FileIntegrity, BackdoorPlugin, AltAccount 等 | +| 高级安全基础设施 | 28 | SessionValidation, CSP, SSRF, XXE, Forensics 等 | +| 网络与流量分析 | 10 | NetworkMonitor, PacketInspection, TokenBucket 等 | +| 基础设施与运维 | 8 | SIEM, LogAnalysis, ThreatIntelligence 等 | +| ML/AI 行为分析 | 4 | BehavioralProfiling, CombatPattern, MovementPattern | +| **总计** | **135+** | | --- -## 3. 监控与指标采集模块 (`com.aluer.monitor` / `com.aluer.metrics`) -负责全天候收集服务器的运行状态,为 AI 决策和控制台提供数据支撑。 +## 一、反作弊 -- 战斗类(15 模块) -- **`ResourceMonitor`** (系统资源监控) - - 采集底层系统的 CPU 使用率、内存消耗、磁盘 I/O 以及当前 TPS 和在线玩家数。 -- **`LogMonitor`** (日志实时分析) - - 实时追踪 Minecraft 服务端(PaperMC)的 `latest.log`,精准捕获异常崩溃堆栈或安全违规日志。 -- **`ProcessMonitor`** (进程守护) - - 监控 Minecraft 核心进程的存活状态,在检测到异常崩溃时触发自动重启机制。 -- **`ConnectionMonitor`** (网络连接监控) - - 统计并分析入站网络连接的频率,快速检测连接洪水(Connection Flood)或 CC 攻击。 -- **`MetricsCollectionService`** (统一指标服务) - - 将各个 Monitor 采集的数据进行标准化和汇总聚合,供前端 Dashboard 和 AI 模型读取。 +完整覆盖 Meteor Client Combat 类别全部 14 个 hack 模块 + AutoClicker。 + +| 类名 | Meteor Hack | 检测维度 | +|------|------------|---------| +| AntiKillAuraService | KillAura | 目标切换频率、Aimbot 角度一致性、极限距离攻击 | +| AntiReachService | Reach | 攻击距离验证、位置回溯 | +| AntiCriticalsService | Criticals | 零速度暴击、暴击率统计、无跳跃暴击 | +| AntiAutoCrystalService | AutoCrystal | 水晶放置/引爆速度、最优位置计算 | +| AntiAutoTotemService | AutoTotem | 图腾换装速度(毫秒级)、连续使用模式 | +| AntiSurroundService | Surround | 四向方块放置速度、防御方块模式 | +| AntiAutoTrapService | AutoTrap | 围笼构建速度、活塞陷阱自动化 | +| AntiAutoArmor | AutoArmor | 多槽位装甲切换速度、背包扫描 | +| AntiChestSwap | ChestSwap | 胸甲/鞘翅互换 tick 检测 | +| AntiAutoLog | AutoLog | 受伤后立即断线、低血量脱战 | +| AntiHitboxes | Hitboxes | 边缘命中率、射线追踪距离分布 | +| AntiBowAimbot | BowAimbot | 移动目标命中率、弹道一致性、瞬发精准 | +| AntiVelocityService | Velocity | 击退幅度异常、抗击退 | +| AntiAutoClickerService | AutoClicker | CPS 统计、点击间隔熵值分析 | +| AntiSpeedService | Speed | 水平移动速度异常(战斗中的移动速度) | + +## 二、反作弊 -- 移动类(18 模块) + +完整覆盖 Meteor Client Movement 类别全部 18 个 hack 模块。 + +| 类名 | Meteor Hack | 检测维度 | +|------|------------|---------| +| AntiFlyDetectionService | Fly | 垂直/水平速度、悬空时间 | +| AntiJesusService | Jesus | 水面/岩浆面移动验证 | +| AntiNoFallService | NoFall | 落地检测、摔落伤害验证 | +| AntiSpeedService | Speed | 水平移动速度异常分析 | +| AntiTimerService | Timer | 游戏 tick 间隔异常 | +| AntiPhaseService | Phase | 方块剪切/穿越检测 | +| AntiBlinkService | Blink | 快速断连躲避伤害 | +| AntiSpiderService | Spider | 无攀爬方块贴墙移动 | +| AntiStepService | Step | 无跳跃跨越完整方块 | +| AntiNoSlowService | NoSlow | 使用物品时移速不减 | +| AntiPacketFlyService | PacketFly | 数据包操控飞行、震荡模式 | +| AntiAirJumpService | AirJump | 半空跳跃数据包 | +| AntiLongJump | LongJump | 极端水平跳跃距离 | +| AntiAntiHunger | AntiHunger | 高活动量零饥饿消耗 | +| AntiFastFall | FastFall | 超终端速度下落 | +| AntiVClip | VClip | 瞬间垂直穿透方块 | +| AntiElytraFlyService | ElytraFly | 鞘翅速度/高度操控 | +| AntiScaffoldService | Scaffold | 方块放置频率/角度/速度 | + +## 三、反作弊 -- 世界/玩家/杂物类(19 模块) + +完整覆盖 Meteor Client World, Player, Misc 类别 hack 模块。 + +| 类名 | Meteor Hack | 类别 | 检测维度 | +|------|------------|------|---------| +| AntiNukerService | Nuker | World | 挖矿速度/范围/模式识别 | +| AntiAutoMineService | AutoMine | World | 自动化采矿行为 | +| AntiSpeedMineService | SpeedMine | World | InstaMine/PacketMine 检测 | +| AntiFastBreakService | FastBreak | Misc | 方块破坏速度异常 | +| AntiFastUseService | FastUse | Misc | 物品使用加速 | +| AntiNoInteractService | NoInteract | Misc | 交互绕过 | +| AntiVeinMinerService | VeinMiner | World | 矿脉自动化挖掘 | +| AntiAutoTool | AutoTool | Player | 即时工具切换 | +| AntiAutoFishService | AutoFish | Player | 钓鱼行为时序分析 | +| AntiChestStealService | ChestSteal | Player | 开箱/取物速度 | +| AntiInventoryManipulationService | InventoryManipulation | Player | 背包操作速度/非法槽位 | +| AntiBaritoneService | Baritone | Player | 路径平滑度/行为重复率 | +| AntiXrayDetectionService | Xray | World | 钻石比率/直线挖掘/暗处精准 | +| AntiGriefDetectionService | Grief | Misc | 方块破坏率/TNT/纵火 | +| AntiFakePlayer | FakePlayer | Misc | 假人实体检测 | +| AntiPistonAura | PistonAura | World | 活塞陷阱自动化 | +| AntiAnchor | Anchor | World | 洞穴锚点防御 | +| AntiStashFinder | StashFinder | World | 储藏箱自动化探测 | +| AntiDupeDetectionService | AntiDupe | Misc | 9 种复制法检测 | + +## 四、服务器漏洞防护(12 模块) + +| 类名 | 防护对象 | 技术手段 | +|------|---------|---------| +| AntiSignExploitService | 告示牌 NBT 漏洞 | JSON 深度/组件有效性校验 | +| AntiBookBanService | 书与笔封禁漏洞 | 页码上限/JSON 层级限制 | +| AntiResourcePackExploitService | 资源包漏洞 | URL 校验/文件大小/格式校验 | +| AntiTabCompleteCrashService | Tab 补全崩溃 | 文本长度限制/嵌套深度限制 | +| AntiOfflineModeSpoofService | 离线 UUID 欺诈 | UUID 冲突检测/IP 关联验证 | +| CrashExploitProtectionService | 崩溃漏洞 | 超大包/NBT 炸弹/书与笔攻击拦截 | +| CrashExploitSignatureDB | 崩溃签名匹配 | 12 种已知签名四级响应 | +| LagMachineDetectionService | 卡服机 | Observer 链/TNT 堆/红石密度 | +| ChunkLoadRateLimiter | 区块加载洪流 | WARN/LIMIT/BLOCK 三级响应 | +| EntityCountEnforcer | 实体数量溢出 | 按区块/玩家/类型自动清理 | +| RedstoneUpdateLimiter | 红石更新风暴 | 降频/冻结/指数退避 | +| PacketFloodProtectionService | 数据包洪水 | 窗口/负载/品牌包限制 | + +## 五、聊天与社交安全(5 模块) + +| 类名 | 防护对象 | +|------|---------| +| ChatFloodProtectionService | 消息洪水(频率/相似度/长度激增) | +| AntiAdvertisementService | IP/域名/群号广告 | +| AntiPhishingLinkService | 钓鱼链接/短链接/可疑域名 | +| AntiCommandAbuseService | 敏感命令滥用/频率限制 | +| PlayerPrivacyService | IP 脱敏/坐标隐藏/日志匿名化 | + +## 六、网络安全(13 模块) + +| 类名 | 防护对象 | +|------|---------| +| DDoSProtectionService | SYN/UDP/ICMP/HTTP/慢速连接/放大攻击 | +| DDoSDefenseCoordinator | 多层 DDoS 防御协调 | +| ProtocolStateValidator | HANDSHAKE/STATUS/LOGIN/PLAY 状态机 | +| BotFingerprintDetector | 登录时序/命名模式/移动熵值 | +| NBTExploitPrevention | NBT 深度/尺寸限制 | +| ConnectionHandshakeValidator | 协议版本/hostname/Ping 洪水/端口扫描 | +| PortScanDetectionService | 端口扫描 | +| BruteForceProtectionService | 暴力破解(多时间窗口) | +| AntiVPNProxyService | 已知 VPN IP/托管 ASN 匹配 | +| DNSTunnelDetectionService | 熵值/Base32 编码/可疑 TLD | +| ReverseShellDetectionService | 50+ shell 模式匹配 | +| ProcessInjectionDetectionService | /proc 扫描/线程异常 | +| ARPSpoofDetectionService | MAC 变更/网关伪造 | + +## 七、主机与访问控制安全(6 模块) + +| 类名 | 防护对象 | +|------|---------| +| FileIntegrityMonitorService | 文件 Hash 基线/实时监控 | +| BackdoorPluginScannerService | 已知恶意类名/远程执行/隐藏命令 | +| ConfigTamperDetectionService | ops/whitelist 实时篡改检测 | +| OPPrivilegeMonitorService | 权限变更/敏感命令审计 | +| AntiAltAccountService | IP 关联/行为相似度/登录模式 | +| AntiNameSpoofService | 管理员/知名玩家昵称伪造 | + +## 八、高级安全基础设施(28 模块) + +| 类名 | 功能 | +|------|------| +| PlayerSessionValidationService | UUID 伪造/正版/离线验证 | +| PluginVerificationService | Hash 对比/未授权修改检测 | +| BackupIntegrityService | SHA-256/文件计数/大小对比 | +| ConnectionThrottleService | IP/时间窗口/递增延迟 | +| GeoBlockService | 按国家/地区 IP 封锁 | +| AntiSkinSpoofService | 模型数据异常/皮肤 URL 检测 | +| JwtAuthService | JWT 令牌签发与验证 | +| AntiBotDetectionService | 机器人名称/加入速率/IP 关联 | +| CSPEnforcementService | 8 种 CSP 响应头强制执行 | +| SSRFProtectionService | 内网 IP/云元数据/协议限制 | +| XXEProtectionService | 实体注入/Billion Laughs 检测 | +| DatabaseFirewallService | SQL 注入/联合查询/时间盲注 | +| DataLossPreventionService | 12 种敏感信息规则+自动脱敏 | +| MemoryProtectionService | JVM 堆/GC/内存泄漏检测 | +| SecureFileDeletionService | 多道覆写(DoD 标准) | +| ForensicsCollectorService | 进程/网络/日志快照 | +| IncidentResponseService | 5 种预定义响应剧本 | +| ThreatHuntingService | 10 种狩猎定义/5 类别 | +| ComplianceScannerService | 7 类 20+ 检查项 | +| ExploitSignatureService | Log4Shell/SQLi/RCE 等 15 种 | +| SecurityOrchestrationService | 本地/边缘/Minecraft 多层编排 | +| SecurityAutomationScheduler | 情报刷新/态势快照/规则同步 | +| HostEnforcementService | iptables/nftables/firewalld 后端 | +| HostIntrusionCountermeasureService | 主机入侵主动对抗 | +| IntrusionDetectionService | 网络入侵检测 | +| IntrusionPreventionSystem | 网络入侵防御 | +| WebApplicationFirewall | HTTP/WS 请求过滤 | +| ZeroTrustArchitectureService | 零信任身份与访问控制 | + +## 九、网络与流量分析(10 模块) + +| 类名 | 功能 | +|------|------| +| NetworkMonitorService | 网络流量实时监控 | +| NetworkSnifferService | 原始数据包捕获分析 | +| NetworkThreatFusionService | 多源威胁情报融合评分 | +| FlowAnalyzerService | NetFlow/IPFIX 流量行为分析 | +| TrafficAnalysisService | 流量模式识别与异常检测 | +| TrafficShapingService | 带宽管理与 QoS 策略 | +| PacketInspectionService | 深度包检测(DPI) | +| ProtocolAnalysisService | 协议合规性与异常分析 | +| TokenBucketRateLimiter | 可复用令牌桶限速原语 | +| FirewallService | iptables/nftables 策略管理 | + +## 十、基础设施与运维安全(8 模块) + +| 类名 | 功能 | +|------|------| +| SIEMService | 安全事件聚合、关联与告警 | +| LogAnalysisService | 日志模式挖掘与异常检测 | +| LogCorrelationService | 跨源日志时间线关联 | +| ThreatIntelligenceService | 开源/商业威胁情报消费 | +| IPReputationService | IP 信誉评分与黑名单查询 | +| SSLTLSCertificateService | 证书有效性/到期/链验证 | +| SecurityBaselineHardeningService | CIS/STIG 基线自动加固 | +| ContainerSecurityService | Docker/K8s 运行时安全 | + +## 十一、ML/AI 行为分析(4 模块) + +| 类名 | 算法/方法 | 输入 | 输出 | +|------|----------|------|------| +| BehavioralProfilingEngine | Isolation Forest, 统计画像 | 玩家事件序列 | 行为异常分数 | +| CombatPatternRecognizer | 序列模式匹配 | 战斗事件序列 | 异常战斗模式标记 | +| MovementPatternAnalyzer | 轨迹分析、路径熵值 | 移动事件序列 | 移动异常分数 | +| ThreatScoreAggregator | 加权聚合、升级逻辑 | 多维度检测结果 | 统一威胁评分 | --- -## 4. 自动化运维与核心调度 (`com.aluer.service` / `com.aluer.schedule`) -统筹全局,确保各模块有序运转,并执行具体的自动化操作。 +## 技术栈详情 -- **`ServerGuardService`** (系统总控台) - - 作为 Spring Boot 的启动核心入口,调度所有监控任务,处理告警分发,协调安全模块与 AI 模块的工作流。 -- **`AutoExecutor`** (指令自动化执行器) - - 接收 AI 或安全模块的决策结果,自动将其转化为服务器指令(如踢出玩家、封禁 IP)并执行。 -- **`RconClient`** (远程控制台客户端) - - 通过安全的 RCON 协议与 Minecraft 服务端通信,无缝下发管理指令。 -- **`ScheduledTaskService`** (计划任务引擎) - - 管理所有周期性任务,例如:定时备份世界数据、清理过期日志、定期生成数据统计报表。 +| 技术 | 版本 | 许可证 | 用途 | +|------|------|--------|------| +| Java | 21 (LTS) | Oracle GPL | 核心编程语言 | +| Spring Boot | 3.2.0 | Apache 2.0 | 应用框架 (IoC, WebSocket, Mail) | +| Spring Shell | 3.1.3 | Apache 2.0 | 交互式 CLI | +| Maven | 3.9.6 | Apache 2.0 | 项目构建与依赖管理 | +| PaperMC API | 1.21.1-R0.1 | MIT | Minecraft 服务端 API | +| SnakeYAML | 2.2 | Apache 2.0 | YAML 配置解析 | +| Smile | 2.6.0 | Apache 2.0 | 机器学习算法 (Isolation Forest) | +| Apache Commons Math | 3.6.1 | Apache 2.0 | 统计计算 | +| Gson | 2.10.1 | Apache 2.0 | JSON 序列化/反序列化 | +| JavaMail | 1.6.2 | GPLv2+CE | SMTP 邮件发送 | --- -## 5. Web API 与交互终端 (`com.aluer.web` / `com.aluer.terminal`) -提供用户友好的交互界面与第三方集成接口。 +## 性能特征 -- **`DashboardController`** (Web 面板 API) - - 提供 RESTful API 接口(如 `/api/status`, `/api/performance`),向前端 Web 界面或 Pterodactyl 等第三方系统暴露实时监控数据、安全日志及配置管理能力。 -- **`AITerminal`** (AI 命令行终端) - - 提供基于 Spring Shell 的交互式控制台。允许管理员通过自然语言(如 `ai 帮我分析一下现在的卡顿原因`)与 AI 助手对话,执行复杂的服务器管理操作。 +### 部署模式对比 + +| 指标 | Plugin 内嵌模式 | External 外部模式 | +|------|----------------|-------------------| +| 通信方式 | WebSocket (localhost) | RCON + 日志 | +| 通信延迟 | < 1ms | 20-200ms | +| 事件吞吐量 | 50,000+ 事件/秒 | 10,000+ 事件/秒 | +| 数据完整性 | 完整(所有 Bukkit 事件) | 有限(仅日志 + RCON) | +| 实时性 | 实时(tick 级响应) | 准实时(秒级延迟) | +| 内存占用(插件部分) | ~50 MB | 0 MB | +| 内存占用(引擎) | ~200 MB | ~200 MB | +| 推荐场景 | 生产服务器 | 监控/备份/测试 | + +### 资源消耗 + +| 场景 | CPU 使用率 | 内存使用 | 网络带宽 | +|------|-----------|---------|---------| +| 空闲 (0 玩家) | < 1% | ~200 MB | < 1 KB/s | +| 低负载 (20 玩家) | 2-5% | ~250 MB | ~50 KB/s | +| 中负载 (50 玩家) | 5-10% | ~300 MB | ~200 KB/s | +| 高负载 (100 玩家) | 10-20% | ~400 MB | ~500 KB/s | +| DDoS 攻击中 | 20-40% | ~500 MB | ~10 MB/s | --- -## 6. 辅助管理与合规模块 -涵盖服务器日常管理的各类垂直功能。 +## Meteor Client 安全覆盖矩阵 -- **`com.aluer.anticheat.AntiCheatService`** (反作弊联动) - - 联动服务器内的反作弊插件,汇总玩家违规行为,进行智能封禁判定。 -- **`com.aluer.vpn.VPNDetectionService`** (代理与 VPN 检测) - - 识别并拦截使用代理 IP 或 VPN 的玩家,防止作弊者绕过 IP 封禁。 -- **`com.aluer.audit.SecurityAuditService`** (安全审计与日志) - - 记录所有管理员的敏感操作指令和安全事件变更,确保符合安全合规要求。 -- **`com.aluer.backup.BackupService`** (自动容灾备份) - - 定时或在遭受攻击前,自动对世界地图(World)、插件配置及数据库进行打包和异地备份。 -- **`com.aluer.chat.ChatFilterService`** (聊天过滤) - - 监控游戏内聊天,过滤违规词汇、广告及钓鱼链接。 -- **`com.aluer.punishment.PunishmentService`** (惩罚管理) - - 统一管理玩家的封禁(Ban)、踢出(Kick)及禁言(Mute)记录。 +本矩阵展示 Aluer ServerGuard 对 Meteor Client 各 hack 模块的检测覆盖情况。 + +### Combat 类别 + +| Meteor Hack | Aluer 检测模块 | 检测方法 | 覆盖度 | +|------------|---------------|---------|--------| +| KillAura | AntiKillAuraService | 目标切换频率 + Aimbot 角度一致性 + 距离模式 | 完整 | +| Reach | AntiReachService | 攻击距离验证 + 位置回溯 | 完整 | +| Criticals | AntiCriticalsService | 零速度暴击 + 暴击率统计 | 完整 | +| AutoCrystal | AntiAutoCrystalService | 水晶放置/引爆速度 + 位置计算 | 完整 | +| AutoTotem | AntiAutoTotemService | 图腾换装速度(毫秒级) | 完整 | +| Surround | AntiSurroundService | 四向方块放置模式 | 完整 | +| AutoTrap | AntiAutoTrapService | 围笼构建速度 | 完整 | +| AutoArmor | AntiAutoArmor | 多槽位装甲切换速度 | 完整 | +| ChestSwap | AntiChestSwap | 胸甲/鞘翅 Tick 检测 | 完整 | +| AutoLog | AntiAutoLog | 受伤后断线模式 | 完整 | +| Hitboxes | AntiHitboxes | 边缘命中率 + 射线分析 | 完整 | +| BowAimbot | AntiBowAimbot | 移动命中率 + 弹道一致性 | 完整 | +| Velocity | AntiVelocityService | 击退幅度 + 抗击退检测 | 完整 | +| AutoClicker | AntiAutoClickerService | CPS 统计 + 熵值分析 | 完整 | +| Anchor | AntiAnchor | 洞穴锚点 Knockback 防御 | 完整 | + +### Movement 类别 + +| Meteor Hack | Aluer 检测模块 | 检测方法 | 覆盖度 | +|------------|---------------|---------|--------| +| Fly | AntiFlyDetectionService | 垂直/水平速度 + 悬空时间 | 完整 | +| Jesus | AntiJesusService | 水面/岩浆面移动验证 | 完整 | +| NoFall | AntiNoFallService | 落地检测 + 伤害验证 | 完整 | +| Speed | AntiSpeedService | 水平速度异常分析 | 完整 | +| Timer | AntiTimerService | Tick 间隔异常 | 完整 | +| Phase | AntiPhaseService | 方块剪切/穿越检测 | 完整 | +| Blink | AntiBlinkService | 快速断连躲避 | 完整 | +| Spider | AntiSpiderService | 无攀爬方块贴墙 | 完整 | +| Step | AntiStepService | 无跳跃跨越方块 | 完整 | +| NoSlow | AntiNoSlowService | 物品使用时移速不减 | 完整 | +| PacketFly | AntiPacketFlyService | 数据包操控 + 震荡模式 | 完整 | +| AirJump | AntiAirJumpService | 半空跳跃数据包 | 完整 | +| LongJump | AntiLongJump | 极端水平跳跃距离 | 完整 | +| AntiHunger | AntiAntiHunger | 高活动量零饥饿消耗 | 完整 | +| FastFall | AntiFastFall | 超终端速度下落 | 完整 | +| VClip | AntiVClip | 瞬间垂直穿透方块 | 完整 | +| ElytraFly | AntiElytraFlyService | 鞘翅速度/高度操控 | 完整 | +| Scaffold | AntiScaffoldService | 方块放置频率/角度 | 完整 | + +### World 类别 + +| Meteor Hack | Aluer 检测模块 | 检测方法 | 覆盖度 | +|------------|---------------|---------|--------| +| Nuker | AntiNukerService | 挖矿速度/范围/模式 | 完整 | +| AutoMine | AntiAutoMineService | 自动化采矿行为 | 完整 | +| SpeedMine | AntiSpeedMineService | InstaMine/PacketMine | 完整 | +| VeinMiner | AntiVeinMinerService | 矿脉自动化挖掘 | 完整 | +| PistonAura | AntiPistonAura | 活塞陷阱自动化 | 完整 | +| StashFinder | AntiStashFinder | 储藏箱自动化探测 | 完整 | +| Xray | AntiXrayDetectionService | 钻石比/直线挖掘/暗处精准 | 完整 | + +### Player 类别 + +| Meteor Hack | Aluer 检测模块 | 检测方法 | 覆盖度 | +|------------|---------------|---------|--------| +| AutoFish | AntiAutoFishService | 钓鱼时序/反应速度 | 完整 | +| ChestSteal | AntiChestStealService | 开箱/取物速度 | 完整 | +| AutoTool | AntiAutoTool | 即时工具切换 | 完整 | +| Baritone | AntiBaritoneService | 路径平滑度/重复率 | 完整 | +| InventoryManipulation | AntiInventoryManipulationService | 操作速度/非法槽位 | 完整 | + +### Misc 类别 + +| Meteor Hack | Aluer 检测模块 | 检测方法 | 覆盖度 | +|------------|---------------|---------|--------| +| FastUse | AntiFastUseService | 物品使用加速 | 完整 | +| FastBreak | AntiFastBreakService | 方块破坏速度异常 | 完整 | +| NoInteract | AntiNoInteractService | 交互绕过 | 完整 | +| FakePlayer | AntiFakePlayer | 假人实体检测 | 完整 | +| AntiDupe | AntiDupeDetectionService | 9 种复制法 | 完整 | +| Grief | AntiGriefDetectionService | 破坏率/TNT/纵火 | 完整 | + +### 覆盖率总结 + +| 类别 | Meteor Client 模块数 | Aluer 覆盖数 | 覆盖率 | +|------|---------------------|-------------|--------| +| Combat | 14 | 14 | 100% | +| Movement | 18 | 18 | 100% | +| World | 7 | 7 | 100% | +| Player | 5 | 5 | 100% | +| Misc | 6 | 6 | 100% | +| **总计** | **50** | **50** | **100%** | --- -## 6.5. 通知与报告模块 (`com.aluer.notification`) -- **`WebhookService`** (Webhook 通知服务) - - 支持 Discord 和 Slack 双通道 Webhook 推送。 - - 安全告警发生时自动发送 Embed 消息,包含告警类型、严重程度、置信度。 - - 支持自定义消息推送,含颜色编码(critical=红色 / warning=橙色 / info=绿色)。 -- **`AttackReportService`** (攻击报告服务) - - 记录最近 500 条攻击事件到内存环形缓冲区。 - - 一键生成 HTML 格式安全事件报告,含时间线、攻击类型、来源 IP、置信度。 - - 报告自动保存到可配置目录,文件名含时间戳。 +## 与同类解决方案对比 + +| 特性 | Aluer ServerGuard | GrimAC | AntiAura | Vulcan | Themis | +|------|------------------|--------|----------|--------|--------| +| 部署方式 | 双模式 (Plugin+External) | Plugin | Plugin | Plugin | Plugin | +| AI 行为分析 | 是 (Isolation Forest) | 否 | 否 | 否 | 否 | +| LLM 集成 | 是 (DeepSeek) | 否 | 否 | 否 | 否 | +| DDoS 防护 | 是 (多层) | 否 | 否 | 否 | 否 | +| 主机安全 | 是 (文件/进程/入侵) | 否 | 否 | 否 | 否 | +| 自愈能力 | 是 (TPS/CPU/内存) | 否 | 否 | 否 | 否 | +| Web 控制台 | 是 (Nebula Console) | 否 | 否 | 否 | 否 | +| SSH 远程管理 | 是 | 否 | 否 | 否 | 否 | +| 威胁情报 | 是 (多源聚合) | 否 | 否 | 否 | 否 | +| 聊天安全 | 是 | 否 | 否 | 否 | 否 | +| 取证/合规 | 是 | 否 | 否 | 否 | 否 | +| Meteor Client 覆盖 | 100% (50/50) | ~60% | ~70% | ~80% | ~50% | +| 开源 | 闭源 | 开源 (GPL) | 付费 | 付费 | 闭源 | +| 目标用户 | 企业/大型社区服 | 通用 | 通用 | 通用 | 通用 | --- -## 7. Web 基础设施层 (`com.aluer.web` / `com.aluer.config`) -- **`HealthService`** (健康检查服务) - - 组件级健康探针:逐一检查 RCON 连接、DeepSeek API、邮件服务、安全引擎、自愈编排。 - - 系统资源信息汇总:JVM 内存使用、堆内存、CPU 负载、运行时间。 - - 兼容 Kubernetes liveness / readiness probe 格式。 -- **`RequestLoggingFilter`** (请求日志过滤器) - - 拦截所有 HTTP 请求,记录慢请求(>1s)和服务器错误(5xx)。 - - 不影响正常请求性能(debug 级别日志)。 -- **`CorsConfig`** (跨域配置) - - 允许 `/api/**` 路径的跨域请求,支持所有 Origin、常用 HTTP 方法和预检缓存。 +## 关键文件清单 -## 8. 数据模型与配置管理 (`com.aluer.model` / `com.aluer.config`) -- **`ServerGuardConfig`** (全局参数配置) - - 映射 `application.yml` 中的参数,包括:各类安全触发阈值、DeepSeek API 密钥、数据库连接及告警邮箱配置等。 -- **`AlertEvent`** (告警数据模型) - - 标准化告警事件结构,包含:告警类型、严重程度、置信度、AI 根因分析及推荐修复动作。 -- **`MetricsData`** (性能指标模型) - - 封装服务器在特定时间点的快照数据,用于历史数据回溯和 AI 时序预测。 +| 文件 | 行数 | 说明 | +|------|------|------| +| `ServerGuardConfig.java` | 1,273 | 完整配置类,含 SuperEvolutionConfig (70+开关) | +| `AlertType.java` | 131 | 告警类型枚举(75种) | +| `AgentMessage.java` | 138 | Agent 通信协议定义 | +| `application.yml` | 316 | 默认 Spring Boot 配置 | +| `AluerPlugin.java` | ~200 | Paper 插件主入口 | +| `security/*.java` (123文件) | ~60,000 | 全部安全检测模块 | +| `ml/*.java` (4文件) | ~2,000 | ML/AI 行为分析模块 | +| `plugin/listener/*.java` (9文件) | ~4,500 | Bukkit 事件监听器 | --- -## 9. V4.0 高级扩展安全模块 (`com.aluer.security`) +## 项目历史 -以下 31 个模块为 V4.0 新增的高级扩展安全模块,涵盖网络层、应用层、主机层和 Minecraft 专属防护: -以下20个安全服务模块为超级进化 (Super Evolution) 版本新增,覆盖身份认证、网络攻防、应用安全、数据保护和运维响应全维度: - -### 9.1 身份与访问控制 -- **`JwtAuthService`** (JWT认证服务) - - 基于 HMAC-SHA256 的 JWT token 创建、验证、吊销。 - - 支持自定义 Claims、过期时间、自动清理。 - - 常量时间签名比对防止时序攻击。 -- **`BruteForceProtectionService`** (反暴力破解服务) - - 三层时间窗口检测 (60s/600s/3600s)。 - - 渐进式登录延迟 (1s-15s),IP 全局阈值监控。 - - 自动账号锁定 + 自动解锁。 - -### 9.2 Minecraft 专项防护 -- **`AntiBotDetectionService`** (反机器人检测) - - 6种机器人命名模式识别,10+已知机器人前缀检测。 - - 加入速度/多账号/客户端品牌/IP洪水多维度评分。 - - Minecraft 登录和状态包频率监控。 -- **`AntiGriefDetectionService`** (反破坏检测) - - 方块破坏/放置速率监控 (150/min爆破, 200/min放置)。 - - 危险方块识别 (TNT/岩浆/水晶/凋零)。 - - 隧道挖掘模式检测,容器掠夺监控,聊天刷屏检测。 - -### 9.3 网络攻击检测 -- **`ReverseShellDetectionService`** (反向Shell检测) - - 50+ 反向Shell命令模式匹配 (bash/python/perl/php/ruby/lua/powershell)。 - - 混淆命令检测 (base64编码/eval/exec)。 - - 进程级Shell指标监控。 -- **`ARPSpoofDetectionService`** (ARP欺骗检测) - - ARP表周期性扫描与基线对比。 - - MAC地址变更/重复MAC/网关欺骗三种攻击检测。 - - 自动识别网关IP并重点监控。 -- **`DNSTunnelDetectionService`** (DNS隧道检测) - - 子域名熵值分析 (Shannon Entropy > 3.8)。 - - Base32/Base64编码子域名识别。 - - 查询频率/类型/TLD多维度评分,可疑域名TLD黑名单。 -- **`ExploitSignatureService`** (漏洞签名检测) - - 15+ 已知漏洞签名 (Log4Shell/JNDI/SQL注入/XSS/路径穿越/反序列化)。 - - Minecraft 专属漏洞 (Book Exploit/Sign Exploit/Chunk Ban/NBT Traversal)。 - - 命令注入和服务端配置篡改检测。 - -### 9.4 Web与API安全 -- **`SSRFProtectionService`** (SSRF防护) - - 内网IP/云元数据端点/危险Scheme检测。 - - DNS Rebinding + 十进制IP绕过 + URL编码绕过防护。 - - 云厂商元数据地址全覆盖 (AWS/GCP/Azure/阿里云/腾讯云)。 -- **`XXEProtectionService`** (XXE防护) - - XML实体注入 + 十亿笑 (Billion Laughs) 攻击检测。 - - 外部实体引用 + 实体扩展炸弹检测。 - - XML自动净化处理。 -- **`CSPEnforcementService`** (CSP强制执行) - - Content-Security-Policy 头自动生成。 - - 8个安全响应头 (CSP/HSTS/X-Frame/X-XSS/Referrer-Policy等)。 - - XSS/Clickjacking反射检测。 -- **`DatabaseFirewallService`** (数据库防火墙) - - SQL注入检测 (UNION/注释/永真条件/堆叠查询/时间盲注)。 - - 危险关键字拦截 (DROP/TRUNCATE/ALTER/INTO OUTFILE)。 - -### 9.5 数据与内存保护 -- **`DataLossPreventionService`** (数据防泄漏) - - 12种敏感数据模式 (邮箱/API Key/密码/SSH Key/JWT/身份证/银行卡/电话号码/数据库连接串/MC Token/RCON密码/IP地址)。 - - 自动脱敏 (Redaction) 功能,支持日志/聊天/配置文件扫描。 -- **`MemoryProtectionService`** (内存保护) - - JVM堆/非堆内存实时监控,GC过载检测。 - - 内存泄漏模式识别 (连续5次以上堆使用率上升)。 - - 自动GC触发和告警。 -- **`ProcessInjectionDetectionService`** (进程注入检测) - - 进程线程数量异常尖峰检测。 - - /proc/{pid}/maps 新内存映射监控,非标准native库检测。 - - /proc/{pid}/fd 文件描述符异常增长检测。 -- **`SecureFileDeletionService`** (安全文件删除) - - DoD 5220.22-M 风格多pass覆写 (0x00/随机/0xFF/0xAA 交替)。 - - 文件截断 + fsync + 删除,支持递归目录安全删除。 - -### 9.6 安全运维与合规 -- **`ForensicsCollectorService`** (取证收集器) - - 6种取证数据采集 (进程列表/网络连接/打开文件/系统日志/MC日志/时间戳快照)。 - - 取证案件 (Case) 管理,自动保存到 forensics/ 目录。 -- **`IncidentResponseService`** (事件响应服务) - - 5套预定义响应剧本 (DDoS攻击/暴力破解/入侵检测/MC漏洞利用/数据泄露)。 - - 自动化动作执行:限流/IP封禁/取证/备份恢复/Token吊销/密钥轮换。 -- **`ThreatHuntingService`** (威胁狩猎服务) - - 10种主动狩猎规则 (异常登录时间/可疑命令/持久化机制/横向移动/提权/数据外泄/挖矿/WebShell/后门账号/快速世界切换)。 - - 分类:MINECRAFT/COMMAND/HOST/NETWORK/WEB。 -- **`ComplianceScannerService`** (合规扫描服务) - - 7大类20+项合规检查 (文件权限/加密标准/认证要求/审计日志/网络安全/MC服务端安全/备份合规)。 - - 自动合规评分 (0-100%) 和修复建议生成。 - ---- - -### 架构总结 -AluerIII 采用 **高度解耦的插件式架构**,底层通过 Spring 的依赖注入(DI)机制紧密配合。系统形成了一套 **实时监测 -> AI 深度分析 -> 策略下发 -> 自动防御** 的完整闭环,极大地降低了 Minecraft 服务器运维人员的安全管理成本。 \ No newline at end of file +| 版本 | 日期 | 里程碑 | +|------|------|--------| +| V5.3 | 2026-05 | 完成 Meteor Client World/Player/Misc 全量对抗 | +| V5.2 | 2026-05 | 完成 Meteor Client Movement 全量对抗 | +| V5.1 | 2026-05 | 完成 Meteor Client Combat 全量对抗 | +| V5.0 | 2026-04 | Agent 架构重构,WebSocket 实时通信 | +| V4.0 | 2026-03 | 基础反作弊框架(KillAura, Reach, Speed 等) | +| V1.0-V3.0 | 2025-2026 | 系统监控、基础防护、告警系统 | diff --git a/docs/USER_MANUAL.md b/docs/USER_MANUAL.md index 653f9c0..3cff591 100644 --- a/docs/USER_MANUAL.md +++ b/docs/USER_MANUAL.md @@ -1,665 +1,607 @@ -# Aluer 服务器安全防护系统 - 用户手册 +# Aluer ServerGuard V5.0 -- 用户手册 ## 目录 + 1. [系统简介](#系统简介) -2. [功能特性](#功能特性) +2. [功能特性概览](#功能特性概览) 3. [安装部署](#安装部署) -4. [快速开始](#快速开始) -5. [AI协作终端](#ai协作终端) -6. [命令参考](#命令参考) -7. [配置说明](#配置说明) -8. [预警系统](#预警系统) -9. [常见问题](#常见问题) +4. [配置说明](#配置说明) +5. [命令参考](#命令参考) +6. [Web 控制台使用](#web-控制台使用) +7. [告警与通知](#告警与通知) +8. [故障排查](#故障排查) +9. [性能调优](#性能调优) +10. [常见问题](#常见问题) --- ## 系统简介 -Aluer 是一款专为 Minecraft PaperMC 服务器设计的安全防护系统,集成了 AI 智能决策、DDoS 防护、入侵检测等多种安全功能。系统采用 Java + Spring Boot 开发,支持通过终端命令行或自然语言与系统交互。 +Aluer ServerGuard 是一款 AI 驱动的 Minecraft PaperMC 服务器全方位安全防护系统。它提供两种运行模式: -### 核心特性 -- 🤖 **AI 智能决策** - 基于 DeepSeek API 的智能威胁分析 -- 🛡️ **多层防御** - DDoS防护、防火墙、入侵检测、VPN检测 -- 📧 **邮件预警** - 实时告警通知管理员 -- 🔄 **自动备份** - 定时自动备份服务器数据 -- 💬 **聊天过滤** - 智能过滤违规内容和广告 -- 🔔 **Webhook 通知** - Discord / Slack 实时推送安全告警 -- 📊 **攻击报告** - 自动生成 HTML 安全事件报告 -- ❤️ **健康检查** - 组件级健康探针,兼容 K8s 部署 +- **Plugin 内嵌模式(推荐)**:以 Paper 插件形式直接在 Minecraft 进程内运行,通过 WebSocket 与外部分析引擎通信。延迟 < 1ms,性能最高。 +- **External 外部监控模式**:以独立进程运行,通过 RCON 和日志监控进行外部防护。 + +本系统包含 135+ 安全模块,覆盖反作弊、DDoS 防御、入侵检测、漏洞防护、聊天安全、主机安全、ML/AI 行为分析等领域。 --- -## 功能特性 +## 功能特性概览 -### 安全防护模块 -| 模块 | 功能说明 | -|------|----------| -| DDoS防护 | 流量清洗、IP封禁、连接限制 | -| 防火墙 | 灵活规则配置、黑白名单 | -| 入侵检测 (IDS/IPS) | 异常行为识别、自动防御拦截 | -| 端口扫描检测 | 防护恶意扫描 | -| IP信誉查询 | 评估IP风险等级 | -| VPN/代理检测 | 识别并封禁VPN用户 | -| 流量分析 | 实时监控网络流量 | -| 数据包检查 (DPI) | 深度包检测与特征匹配 | +### 核心功能 -### 高级进阶防护 -| 模块 | 功能说明 | -|------|----------| -| WAF防火墙 | 针对Web面板和API的恶意请求防护 | -| 蜜罐系统 (Honeypot) | 诱导并捕获恶意攻击者 | -| 零信任架构 (ZTA) | 强制身份验证、严格的权限控制 | -| Cloudflare 集成 | 自动同步真实玩家IP,联动CDN防御 | -| 反作弊集成 | 自动联动服务端反作弊插件,智能判定 | -| 威胁情报中心 | 全局恶意IP库共享与实时更新 | - -### AI 自主防御 -- 自动威胁检测与分类 -- 智能防御策略选择 -- 预测性维护建议 -- 自动执行防御动作 - -### 服务器管理 -- 定时自动备份(世界、插件、配置) -- 玩家管理(踢出、封禁、解封) -- 世界管理(动态加载、卸载) -- 高级性能监控与分析 (Profiler) -- 安全审计与数据导出 (Data Export) +| 功能 | 说明 | +|------|------| +| AI 行为分析 | 基于 Isolation Forest 的异常检测,自动识别异常玩家行为 | +| DeepSeek 集成 | 大模型自动分析安全告警,生成防御策略并自主执行 | +| 全量反作弊 | 100% 覆盖 Meteor Client 全部 50 个 hack 模块 | +| DDoS 防御 | 多层协同防御(SYN/UDP/ICMP/HTTP/Minecraft 专属) | +| 自愈系统 | TPS/CPU/内存异常自动恢复,自动白名单、自动备份 | +| Web 控制台 | Nebula Console 实时仪表盘,SSH 远程管理 | +| 邮件告警 | SMTP 邮件通知,支持速率限制和多收件人 | +| 备份管理 | 定时全量/增量备份,完整性校验(SHA-256) | +| 定时任务 | 每日重启/清 lag/周备份,全自动调度 | +| 聊天过滤 | 广告/钓鱼/洪水/敏感词检测,自动禁言/踢出 | --- ## 安装部署 ### 环境要求 -- Java 17 或更高版本 -- Ubuntu/Debian 服务器 -- 2GB+ 可用内存 -- 10GB+ 可用磁盘空间 -### 安装步骤 +| 依赖 | 最低版本 | 说明 | +|------|---------|------| +| Java JDK | 21 | 编译和运行 | +| PaperMC | 1.21.1 | Minecraft 服务端(Plugin 模式) | +| 操作系统 | Linux (推荐) / Windows | 64 位 | +| 内存 | 512 MB 可用 | 引擎占用 ~200MB | +| 磁盘 | 100 MB | 不含日志和备份 | + +### 方式一:Plugin 内嵌模式(推荐) + +**步骤 1:编译项目** -#### 1. 上传文件到服务器 ```bash -# 在本地打包 -cd /path/to/AluerIII +cd /opt/AluerIII ./apache-maven-3.9.6/bin/mvn package -DskipTests - -# 上传 jar 包和配置到服务器 -scp target/AluerServerGuard-V4.0.jar user@your-server:/opt/aluer/ -scp start.sh user@your-server:/opt/aluer/ ``` -#### 2. 配置系统服务 +**步骤 2:安装插件** + ```bash -# 创建 systemd 服务文件 -sudo nano /etc/systemd/system/aluer.service +cp target/serverguard-4.0.0.jar /opt/minecraft/plugins/AluerServerGuard.jar ``` -写入以下内容: -```ini -[Unit] -Description=Aluer ServerGuard -After=network.target +**步骤 3:创建插件配置** `/opt/minecraft/plugins/AluerServerGuard/config.yml`: -[Service] -Type=simple -User=minecraft -WorkingDirectory=/opt/aluer -ExecStart=/usr/bin/java -jar /opt/aluer/AluerServerGuard-V4.0.jar -Restart=on-failure -RestartSec=10 - -[Install] -WantedBy=multi-user.target +```yaml +server-url: ws://localhost:8080/agent ``` -#### 3. 启动服务 +**步骤 4:配置环境变量(可选但推荐)** + ```bash -sudo systemctl daemon-reload -sudo systemctl enable aluer -sudo systemctl start aluer - -# 查看状态 -sudo systemctl status aluer +export DEEPSEEK_API_KEY="sk-your-api-key" +export ALUER_ALERT_SMTP_USERNAME="your-email@qq.com" +export ALUER_ALERT_SMTP_PASSWORD="your-smtp-password" +export ALUER_ALERT_EMAIL_PRIMARY="admin@example.com" +export RCON_PASSWORD="your-rcon-password" ``` ---- +**步骤 5:启动 ServerGuard 引擎** -## 快速开始 - -### 启动系统 ```bash -# 方式1: 直接运行 -java -jar AluerServerGuard-V4.0.jar - -# 方式2: 使用启动脚本 -./start.sh - -# 方式3: 使用系统服务 -sudo systemctl start aluer +java -jar target/serverguard-4.0.0.jar ``` -### 首次使用 -系统启动后会进入交互式终端: +**步骤 6:启动 Minecraft 服务器** -``` -╔══════════════════════════════════════════════════╗ -║ 欢迎使用 Aluer 服务器安全防护系统 ║ -╠══════════════════════════════════════════════════╣ -║ 输入 help 查看可用命令 ║ -║ 输入 ai <命令> 使用AI智能助手 ║ -╚══════════════════════════════════════════════════╝ -aluer> +```bash +cd /opt/minecraft +java -Xms4G -Xmx4G -jar paper-1.21.11.jar ``` ---- - -## AI协作终端 - -Aluer 的核心特性是可以用自然语言与系统对话。 - -### 使用方式 -在终端输入 `ai` 后跟你的需求: +**验证安装成功:** +查看 Minecraft 控制台输出,应该看到: ``` -aluer> ai 测试一下服务器 -``` -系统会自动执行完整服务器测试。 - -``` -aluer> ai 开启防御 -``` -系统会开启AI自主防御模式。 - -### 常用对话示例 -| 你说 | 系统执行 | -|------|----------| -| 测试一下服务器 | 执行完整测试 | -| 开启防御 | 开启AI防御 | -| 查看安全状态 | 显示安全概览 | -| 帮我备份 | 查看备份记录 | -| 查看世界 | 列出所有世界 | -| 发送预警邮件 | 手动触发预警 | - ---- - -## 命令参考 - -### 基础命令 - -#### help - 帮助 -``` -aluer> help -``` -显示所有可用命令。 - -#### status - 服务器状态 -``` -aluer> status -``` -显示服务器整体状态,包括CPU、内存、连接数等。 - -#### test - 测试服务器 -``` -aluer> test # 完整测试 -aluer> test cpu # 仅CPU测试 -aluer> test memory # 仅内存测试 -aluer> test network # 仅网络测试 -aluer> test security # 仅安全测试 +[AluerServerGuard] Aluer ServerGuard Agent v5.0.0 +[AluerServerGuard] 轻量数据采集前端 - 连接外部 ServerGuard 引擎 +[AluerServerGuard] WebSocket connected to ws://localhost:8080/agent ``` -### 安全命令 - -#### security - 安全状态 +查看 ServerGuard 控制台输出,应该看到: ``` -aluer> security # 安全总览 -aluer> security ddos # DDoS防护状态 -aluer> security firewall # 防火墙状态 -aluer> security intrusion # 入侵检测状态 -aluer> security threats # AI威胁检测 -aluer> security vpn # VPN检测状态 -aluer> security chat # 聊天过滤状态 +Agent connected: agent-xxxx +Agent handshake completed: agent-xxxx ``` -#### defense - 防御管理 -``` -aluer> defense # 查看防御状态 -aluer> defense on # 开启AI防御 -aluer> defense off # 关闭AI防御 -aluer> defense list # 查看防御策略 -aluer> defense level high # 设置防御等级 +### 方式二:External 外部监控模式 + +**步骤 1:编译** + +```bash +./apache-maven-3.9.6/bin/mvn package -DskipTests ``` -### 管理命令 +**步骤 2:配置 `application.yml`** -#### backup - 备份管理 -``` -aluer> backup # 查看备份记录 -aluer> backup create # 创建新备份 -aluer> backup status # 备份服务状态 -aluer> backup start # 启动定时备份 -``` - -#### kick - 踢出玩家 -``` -aluer> kick PlayerName -``` - -#### ban - 封禁玩家 -``` -aluer> ban PlayerName # 封禁玩家 -aluer> ban PlayerName 作弊原因 # 带原因封禁 -``` - -#### unban - 解封玩家 -``` -aluer> unban PlayerName -``` - -### 世界管理 - -#### world - 世界管理 -``` -aluer> world # 查看世界列表 -aluer> world load world_nether # 加载世界 -aluer> world unload world_nether # 卸载世界 -``` - -### 网络分析 - -#### network - 网络分析 -``` -aluer> network # 网络统计 -aluer> network geoip 1.2.3.4 # IP地理位置 -aluer> network reputation 1.2.3.4 # IP信誉查询 -aluer> network ports # 端口扫描检测 -``` - -### 预警系统 - -#### alert - 邮件预警 -``` -aluer> alert # 查看预警状态 -aluer> alert test # 发送测试邮件 -aluer> alert send 服务器异常 # 手动发送告警 -``` - -### 监控命令 - -#### metrics - 性能指标 -``` -aluer> metrics # 指标摘要 -aluer> metrics counters # 查看计数器 -aluer> metrics gauges # 查看计量器 -``` - -#### audit - 安全审计 -``` -aluer> audit # 最近审计事件 -aluer> audit recent 20 # 查看最近20条 -aluer> audit summary # 审计摘要 -``` - -#### tasks - 计划任务 -``` -aluer> tasks # 查看任务列表 -aluer> tasks start # 启动任务服务 -``` - -### AI 命令 - -#### ask - 向AI提问 -``` -aluer> ask 如何提高服务器安全性? -``` - ---- - -## Web 控制面板与 API - -Aluer 内置了轻量级的 Web Dashboard 和 RESTful API,方便与 Pterodactyl 等第三方服务器面板集成,或通过网页端实时查看状态。 - -### 访问方式 -启动系统后,可通过 HTTP 协议访问系统 API 服务。 - -### 常用 API 接口 -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/status` | GET | 获取系统运行状态及时间戳 | -| `/api/server/info` | GET | 获取 Minecraft 服务器名称与版本信息 | -| `/api/performance` | GET | 获取性能指标(TPS, CPU, 内存) | -| `/api/command/execute` | POST | 远程执行 RCON 命令 (参数: `command`) | -| `/api/backup/list` | GET | 获取所有服务器备份列表 | -| `/api/backup/create` | POST | 触发创建新备份 (参数: `name`) | -| `/api/punishment/list` | GET | 获取封禁与禁言记录统计 | - -*(提示:在生产环境中,请务必通过反向代理并配置鉴权,以保护 API 接口安全)* - -### 系统健康检查 API(新增) - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/health` | GET | 完整健康报告(组件状态 + JVM 内存 + CPU 负载) | -| `/api/health/live` | GET | 存活探针,返回 `{"status":"UP"}` | -| `/api/health/ready` | GET | 就绪探针,检查 RCON 可用性 | - -**健康检查响应示例**: -```json -{ - "status": "HEALTHY", - "uptimeSeconds": 86400, - "components": { - "rcon": {"status": "UP"}, - "deepseek-ai": {"status": "UP", "model": "deepseek-chat"}, - "email-alert": {"status": "UP"}, - "security": {"status": "UP", "kernelEnabled": true}, - "self-healing": {"status": "UP", "dryRun": true} - }, - "system": { - "memory": {"usedMB": 320, "maxMB": 4096}, - "heapUsedMB": 180, - "systemCpuLoad": 12.5 - } -} -``` - -### 通知与攻击报告 API(新增) - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/attacks/recent?limit=20` | GET | 最近攻击记录列表 | -| `/api/attacks/report` | POST | 生成并保存 HTML 攻击报告到 `./reports/` 目录 | -| `/api/webhook/test` | POST | 向已配置的 Discord/Slack 发送测试消息 | - -**Webhook 配置**(`application.yml`): ```yaml serverguard: - webhook: - enabled: false # 设为 true 启用 - discord-url: ${ALUER_WEBHOOK_DISCORD:} # Discord Webhook URL - slack-url: ${ALUER_WEBHOOK_SLACK:} # Slack Webhook URL - report: - dir: ./reports # 攻击报告输出目录 + mode: external + minecraft: + working-dir: /opt/minecraft + rcon: + enabled: true + host: localhost + port: 25575 + password: "${RCON_PASSWORD}" + process-name: paper-1.21.11.jar ``` -**环境变量**: +**步骤 3:在 Minecraft `server.properties` 中启用 RCON** + +```properties +enable-rcon=true +rcon.port=25575 +rcon.password=your-rcon-password-here +``` + +**步骤 4:启动 ServerGuard** + ```bash -export ALUER_WEBHOOK_DISCORD="https://discord.com/api/webhooks/xxx/yyy" -export ALUER_WEBHOOK_SLACK="https://hooks.slack.com/services/xxx/yyy/zzz" +java -jar target/serverguard-4.0.0.jar ``` -### 高级扩展安全模块 API(V4.0 完整版) - -#### 身份认证与访问控制 - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/auth/status` | GET | JWT 认证状态(活跃Token数、已吊销Token数) | -| `/api/security/brute-force/status` | GET | 暴力破解防护状态(锁定账号、检测统计) | - -#### Minecraft 专项防护 - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/anti-bot/status` | GET | 反机器人检测状态(被拦截IP、Bot分数) | -| `/api/security/anti-grief/status` | GET | 反破坏检测状态(被标记玩家、方块破坏率) | - -#### 网络攻击监控 - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/reverse-shell/status` | GET | 反向Shell检测状态 | -| `/api/security/arp-spoof/status` | GET | ARP欺骗检测状态(MAC变更记录) | -| `/api/security/dns-tunnel/status` | GET | DNS隧道检测状态 | -| `/api/security/exploit-signature/status` | GET | 漏洞签名检测统计 | -| `/api/security/exploit-signature/scan` | POST | 扫描内容中的漏洞签名 (参数: `content`, `source`) | - -#### Web与应用安全 - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/ssrf/status` | GET | SSRF防护状态 | -| `/api/security/xxe/status` | GET | XXE防护状态 | -| `/api/security/csp/status` | GET | CSP违规统计 | -| `/api/security/csp/headers` | GET | 获取推荐的安全响应头 | -| `/api/security/database-firewall/status` | GET | 数据库防火墙状态 | -| `/api/security/dlp/status` | GET | 数据防泄漏检测统计 | - -#### 系统保护 - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/memory/status` | GET | JVM内存保护状态(堆使用率、GC统计) | -| `/api/security/process-injection/status` | GET | 进程注入检测状态 | -| `/api/security/secure-delete/status` | GET | 安全文件删除统计 | - -#### 安全运维 - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/forensics/status` | GET | 取证案件列表与证据统计 | -| `/api/security/incident-response/status` | GET | 事件响应状态(活跃事件、剧本列表) | -| `/api/security/threat-hunting/status` | GET | 威胁狩猎状态(最近狩猎结果) | -| `/api/security/compliance/status` | GET | 合规扫描结果(评分、通过/失败项) | - -#### Minecraft 专属安全(V4.0) - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/anti-xray/status` | GET | X-ray透视检测状态(可疑玩家、钻石/石头比) | -| `/api/security/anti-fly/status` | GET | 飞行/速度外挂检测状态 | -| `/api/security/anti-dupe/status` | GET | 物品复制检测状态(堆叠异常、高价值物品暴涨) | -| `/api/security/crash-exploit/status` | GET | 崩溃漏洞防护状态(超大包、NBT炸弹、书与笔攻击) | -| `/api/security/lag-machine/status` | GET | 卡服机检测状态(Observer链、TNT堆、红石密度) | - -#### V4.0 新增安全 API - -| 接口路径 | 方法 | 说明 | -|----------|------|------| -| `/api/security/geo-block/status` | GET | 地理IP封锁状态(拦截计数、黑白名单大小) | -| `/api/security/session-validation/status` | GET | 玩家会话验证状态(UUID检测、重放攻击计数) | -| `/api/security/plugin-verification/status` | GET | 插件完整性校验状态(已验证、失败、恶意检测) | -| `/api/security/connection-throttle/status` | GET | 连接速率限制状态(活跃IP、已拦截、已延迟) | -| `/api/security/backup-integrity/status` | GET | 备份完整性验证状态(通过/失败/损坏计数) | -| `/api/security/anti-skin-spoof/status` | GET | 皮肤伪造检测状态(冒充者、可疑URL、变更频率) | - --- ## 配置说明 ### 配置文件位置 -主配置文件: `src/main/resources/application.yml` -### 核心配置项 +- **ServerGuard 引擎配置**:`application.yml`(与 JAR 同目录或 classpath) +- **Plugin 插件配置**:`plugins/AluerServerGuard/config.yml` +- **环境变量**:通过 `${ENV_VAR:default}` 语法覆盖 -#### DeepSeek AI 配置 -```yaml -deepseek: - api-key: sk-your-api-key # API密钥 - enabled: true # 是否启用 - model: deepseek-chat # 模型名称 -``` +### 配置节导航 -#### RCON 配置(用于连接Minecraft服务器) -```yaml -rcon: - enabled: true - host: localhost - port: 25575 - password: your-password -``` +`application.yml` 包含以下顶配配置节: -#### 邮件预警配置 -```yaml -alert: - email: - enabled: true - smtp-host: smtp.qq.com - smtp-port: 587 - username: your-email@qq.com - password: your-auth-code - from: your-email@qq.com - to: - - admin@example.com - - backup@example.com -``` +| 配置节 | 说明 | 关键参数 | +|--------|------|---------| +| `serverguard.mode` | 运行模式 | `plugin` / `external` | +| `serverguard.minecraft` | Minecraft 进程管理 | working-dir, process-name, rcon | +| `serverguard.monitor` | 监控阈值 | tps-threshold, cpu-threshold, memory-threshold | +| `serverguard.alert` | 邮件告警 | smtp 配置, 收件人, 速率限制 | +| `serverguard.ai` | AI/ML + DeepSeek | 隔离森林, 预测, 自动执行 | +| `serverguard.security` | 安全防御总配置 | 含 15 个子配置节 | +| `serverguard.dashboard` | Web 控制台 | SSH 网关, 刷新间隔 | +| `serverguard.backup` | 自动备份 | 备份目录, 压缩, 保留数量 | +| `serverguard.schedule` | 定时任务 | 每日重启, 周备份, 清 lag | +| `serverguard.chat-filter` | 聊天过滤 | 广告/钓鱼/洪水/禁言 | +| `serverguard.afk` | AFK 管理 | 超时时间, AFK 区域, 自动踢出 | -#### 安全模块配置 -```yaml -security: - ddos: - enabled: true - threshold: 1000 # 连接数阈值 - firewall: - enabled: true - intrusion: - enabled: true - alert-level: MEDIUM -``` +### 快速配置示例 -#### 备份配置 -```yaml -backup: - enabled: true - interval-hours: 6 # 备份间隔(小时) - backup-dir: ./backups - world-dir: /path/to/server/world - backup-plugins: true - backup-config: true -``` - -#### 高级扩展安全模块开关(V4.0) - -以下 31 个高级扩展安全模块均可通过 `application.yml` 中的 `serverguard.security.super-evolution` 节点独立控制开关。设为 `false` 即可关闭该模块,相关检测逻辑将被跳过,不消耗额外性能。 +**最小化生产配置:** ```yaml serverguard: + mode: plugin + minecraft: + working-dir: /opt/minecraft + rcon: + password: "${RCON_PASSWORD}" + monitor: + tps-threshold: 15 + cpu-threshold: 80.0 + memory-threshold: 85.0 security: + enabled: true super-evolution: - # === V4.0 高级扩展安全模块(20个) === - jwt-auth: true # JWT身份认证与令牌管理 - brute-force: true # 暴力破解防护(多时间窗口检测) - anti-bot: true # 反机器人检测(Bot名称/加入速率/IP关联) - reverse-shell: true # 反向Shell检测(50+ shell模式匹配) - arp-spoof: true # ARP欺骗检测(MAC变更/网关伪造) - dns-tunnel: true # DNS隧道检测(熵值/Base32编码/可疑TLD) - exploit-signature: true # 漏洞签名检测(Log4Shell/SQLi/RCE等15种) - ssrf: true # SSRF防护(内网IP/云元数据/协议限制) - xxe: true # XXE防护(实体注入/Billion Laughs检测) - csp: true # CSP安全头强制执行(8种响应头) - database-firewall: true # 数据库防火墙(SQL注入/联合查询/时间盲注) - dlp: true # 数据防泄漏(12种敏感信息规则+自动脱敏) - memory-protection: true # JVM内存保护(堆/GC/内存泄漏检测) - process-injection: true # 进程注入检测(/proc扫描/线程异常) - secure-delete: true # 安全文件删除(多道覆写DoD标准) - forensics: true # 取证收集(进程/网络/日志快照) - incident-response: true # 事件响应(5种预定义响应剧本) - threat-hunting: true # 威胁狩猎(10种狩猎定义/5个类别) - compliance: true # 合规扫描(7类20+检查项) - anti-grief: true # 反破坏检测(方块破坏率/TNT/纵火/偷箱) - # === Minecraft 专属防护模块(5个) === - anti-xray: true # X-ray透视检测(钻石比/直线挖掘/暗处精准) - anti-fly: true # 飞行外挂检测(垂直/水平速度/悬空时间) - anti-dupe: true # 物品复制检测(堆叠异常/高价值暴涨/9种复制法) - crash-exploit: true # 崩溃漏洞防护(超大包/NBT炸弹/书与笔攻击) - lag-machine: true # 卡服机检测(Observer链/TNT堆/红石密度) - # === V4.0 新增模块(6个) === - geo-block: true # 地理IP封锁(按国家/地区拦截) - session-validation: true # 玩家会话验证(UUID伪造/正版/离线检测) - plugin-verification: true # 插件完整性校验(Hash对比/未授权修改) - connection-throttle: true # 连接速率限制(IP/时间窗口/递增延迟) - backup-integrity: true # 备份完整性校验(SHA-256/文件计数/大小对比) - anti-skin-spoof: true # 皮肤伪造检测(模型数据异常/皮肤URL检测) + anti-kill-aura: true + anti-reach: true + anti-speed: true + anti-fly: true + anti-xray: true + anti-dupe: true + # ... 按需启用其他模块 ``` -**开关说明:** -- 所有模块默认 `true`(开启),可根据需要设为 `false` 关闭 -- 关闭模块后,对应的 API 端点仍可访问但返回空数据 -- 关闭不需要的模块可以降低 CPU/内存开销 -- 修改配置后需重启服务生效 +**启用全部反作弊模块:** + +在 `super-evolution` 节中将所有 `anti-*` 开关设置为 `true`。默认配置中全部模块已默认启用。 + +### 环境变量参考 + +| 变量名 | 说明 | 必需 | +|--------|------|------| +| `SERVERGUARD_MODE` | 运行模式(覆盖 mode 配置) | 否 | +| `DEEPSEEK_API_KEY` | DeepSeek API 密钥 | 建议(AI 功能) | +| `DEEPSEEK_BASE_URL` | DeepSeek API 地址 | 否 | +| `DEEPSEEK_MODEL` | 模型名称 | 否 | +| `RCON_PASSWORD` | Minecraft RCON 密码 | 是(External 模式) | +| `ALUER_ALERT_SMTP_USERNAME` | SMTP 发件邮箱 | 建议(告警功能) | +| `ALUER_ALERT_SMTP_PASSWORD` | SMTP 密码/授权码 | 建议(告警功能) | +| `ALUER_ALERT_EMAIL_PRIMARY` | 主告警接收邮箱 | 建议(告警功能) | +| `ALUER_ALERT_EMAIL_SECONDARY` | 备用告警接收邮箱 | 否 | +| `ALUER_CLOUDFLARE_ZONE_ID` | Cloudflare Zone ID | 否 | +| `ALUER_CLOUDFLARE_API_KEY` | Cloudflare API Key | 否 | +| `ALUER_CLOUDFLARE_EMAIL` | Cloudflare 账号邮箱 | 否 | +| `ALUER_WEBHOOK_DISCORD` | Discord Webhook URL | 否 | +| `ALUER_WEBHOOK_SLACK` | Slack Webhook URL | 否 | --- -## 预警系统 +## 命令参考 -### 预警类型 -系统会自动检测并发送预警: -- ⚠️ 服务器进程停止 -- ⚠️ TPS过低 -- ⚠️ CPU使用率过高 -- ⚠️ 内存使用率过高 -- ⚠️ 连接数异常(DDoS攻击) -- ⚠️ 日志中发现攻击行为 -- ⚠️ 备份失败 +### Spring Shell CLI 命令 -### 手动触发预警 -```bash -aluer> alert send 服务器可能遭受攻击 +ServerGuard 引擎启动后提供交互式命令行(Spring Shell),支持以下命令: + +#### 系统状态 + +| 命令 | 说明 | +|------|------| +| `status` | 显示系统运行状态(运行时间、内存、活跃线程) | +| `tps` | 显示当前 TPS 和 MSPT | +| `players` | 列出在线玩家 | +| `metrics` | 显示完整性能指标 | + +#### 安全管理 + +| 命令 | 说明 | +|------|------| +| `ban ` | 封禁玩家 | +| `ban-ip ` | 封禁 IP | +| `kick [reason]` | 踢出玩家 | +| `unban ` | 解封玩家 | +| `whitelist on\|off` | 启用/关闭白名单 | +| `whitelist add ` | 添加白名单 | +| `whitelist remove ` | 移除白名单 | + +#### 模块管理 + +| 命令 | 说明 | +|------|------| +| `modules list` | 列出所有安全模块及状态 | +| `modules enable ` | 启用指定模块 | +| `modules disable ` | 禁用指定模块 | +| `modules status ` | 查看模块详细状态 | + +#### AI 控制 + +| 命令 | 说明 | +|------|------| +| `ai status` | 查看 AI 引擎状态 | +| `ai analyze ` | 对指定玩家进行 AI 行为分析 | +| `ai report` | 生成当前安全态势报告 | + +#### 系统控制 + +| 命令 | 说明 | +|------|------| +| `save-all` | 强制保存所有世界 | +| `clear-lag` | 清理所有非玩家实体 | +| `backup now` | 立即执行一次备份 | +| `restart [delay]` | 计划重启服务器 | +| `reload-config` | 重新加载配置文件 | + +### Minecraft 游戏内命令(Plugin 模式) + +当使用 Plugin 模式时,具有 OP 权限的玩家可以在游戏内使用以下命令: + +| 命令 | 权限 | 说明 | +|------|------|------| +| `/aluer status` | aluer.status | 显示防护状态 | +| `/aluer tps` | aluer.status | 显示 TPS 信息 | +| `/aluer alerts` | aluer.alerts | 查看最近告警 | +| `/aluer check ` | aluer.check | 对玩家执行安全检查 | +| `/aluer report ` | aluer.report | 举报可疑玩家 | +| `/aluer reload` | aluer.admin | 重新加载配置 | + +--- + +## Web 控制台使用 + +### Nebula Console + +ServerGuard 内置 Web 控制台(Nebula Console),提供实时仪表盘和远程管理功能。 + +**访问地址**:`http://:8080` + +**主要功能:** + +1. **实时仪表盘** — TPS、CPU、内存、在线玩家、告警数实时图表 +2. **玩家列表** — 在线玩家详情、威胁评分、行为日志 +3. **告警中心** — 历史告警查询、筛选、DeepSeek 分析结果 +4. **模块管理** — 查看/启用/禁用各安全模块 +5. **SSH 网关** — 通过 Web 终端直接操作服务器 +6. **配置管理** — 在线修改配置(需重启生效) + +### SSH 网关配置 + +```yaml +serverguard: + dashboard: + ssh-gateway: + enabled: true + session-timeout-minutes: 30 + max-sessions: 6 + command-timeout-seconds: 25 + strict-host-key-checking: false + allow-private-key-paste: true + require-engine-handshake: true + handshake-ttl-seconds: 30 ``` -### 测试邮件系统 -```bash -aluer> alert test +**使用 SSH 网关:** + +1. 打开 Nebula Console +2. 点击 "SSH Terminal" +3. 输入目标主机、端口、用户名 +4. 粘贴 SSH 私钥或输入密码 +5. 执行引擎握手验证 +6. 获得交互式 Shell + +--- + +## 告警与通知 + +### 告警渠道 + +| 渠道 | 配置 | 说明 | +|------|------|------| +| 邮件 | `serverguard.alert.email.*` | SMTP 邮件通知 | +| Discord | `serverguard.webhook.discord-url` | Discord Webhook | +| Slack | `serverguard.webhook.slack-url` | Slack Webhook | +| 控制台 | 默认启用 | Spring Shell/日志输出 | +| Web 控制台 | `serverguard.dashboard.enabled` | Nebula Console 实时推送 | + +### 告警级别 + +| 级别 | 说明 | 自动响应 | +|------|------|---------| +| INFO | 信息性通知 | 无 | +| WARNING | 潜在威胁 | 记录日志 | +| CRITICAL | 严重威胁 | 自动防御(如配置) | +| EMERGENCY | 紧急情况 | 全自动响应 + 通知 | + +### 邮件告警配置 + +```yaml +serverguard: + alert: + enabled: true + email: + smtp-host: smtp.qq.com # QQ邮箱 + smtp-port: 587 + username: "your-email@qq.com" + password: "授权码(非密码)" + to: + - "admin@example.com" + - "backup-admin@example.com" + rate-limit: + per-type-seconds: 300 # 同类型告警 5 分钟内只发一次 + max-emails-per-minute: 10 # 每分钟最多 10 封 +``` + +**QQ 邮箱 SMTP 配置步骤:** +1. 登录 QQ 邮箱 +2. 设置 -> 账户 -> POP3/IMAP/SMTP 服务 +3. 开启 SMTP 服务 +4. 获取授权码(不是 QQ 密码) +5. 将授权码填入 `password` 字段 + +--- + +## 故障排查 + +### 常见问题与解决方案 + +#### 1. Plugin 无法连接到 ServerGuard + +**症状**:Minecraft 控制台显示 "Failed to connect to ServerGuard" + +**排查步骤**: +1. 确认 ServerGuard 引擎已启动:`ps aux | grep serverguard` +2. 确认端口 8080 未被占用:`netstat -tlnp | grep 8080` +3. 检查 `config.yml` 中的 `server-url` 是否正确 +4. 检查防火墙是否阻止了 localhost 连接 +5. 查看 ServerGuard 日志:`tail -f /var/log/serverguard.log` + +#### 2. DeepSeek API 连接失败 + +**症状**:日志显示 "DeepSeek API error" + +**排查步骤**: +1. 确认 API Key 正确设置:`echo $DEEPSEEK_API_KEY` +2. 测试 API 连通性:`curl -H "Authorization: Bearer $DEEPSEEK_API_KEY" https://api.deepseek.com/v1/models` +3. 检查 API 额度是否用尽 +4. 检查网络是否需要代理 + +#### 3. TPS 持续偏低 + +**症状**:告警 "Low TPS" 频繁触发 + +**排查步骤**: +1. 使用 `/aluer tps` 查看实时 TPS +2. 检查实体数量:`/aluer status` 中的 Entity Count +3. 手动清理实体:`clear-lag` 命令 +4. 调整 `entity-count-enforcer` 阈值 +5. 检查 `redstone-update-limiter` 是否启用 + +#### 4. 误判/误封 + +**症状**:正常玩家被标记为作弊 + +**排查步骤**: +1. 使用 `ai analyze ` 查看 AI 分析结果 +2. 检查该玩家触发了哪些检测模块 +3. 调整对应模块的检测阈值 +4. 将玩家加入白名单(临时方案) +5. 查看 DeepSeek 告警分析以了解误判原因 + +#### 5. 构建失败 + +**症状**:`mvn compile` 或 `mvn test` 失败 + +**排查步骤**: +1. 确认 Java 版本:`java -version`(需要 Java 21) +2. 清理构建缓存:`./apache-maven-3.9.6/bin/mvn clean` +3. 检查 PaperMC API 仓库是否可访问 +4. 查看完整错误日志:`./apache-maven-3.9.6/bin/mvn compile -e` + +--- + +## 性能调优 + +### TPS 优化 + +```yaml +serverguard: + monitor: + tps-threshold: 15 # 根据服务器性能调整 + + security: + super-evolution: + # 在低性能服务器上可选择性禁用高开销模块 + entity-count-enforcer: true # 自动清理过多实体 + redstone-update-limiter: true # 限制红石更新 + chunk-load-rate-limiter: true # 限制区块加载 +``` + +### 内存优化 + +```yaml +serverguard: + minecraft: + java-opts: -Xms4G -Xmx4G # 根据实际内存调整 + + monitor: + memory-threshold: 85.0 # 内存告警阈值 + + ai: + sliding-window-size: 100 # 减小窗口降低内存占用 +``` + +### AI 性能调优 + +```yaml +serverguard: + ai: + use-isolation-forest: true # 隔离森林(轻量) + use-prediction: false # 在低配服务器上关闭预测 + sliding-window-size: 50 # 减小窗口提高响应速度 + anomaly-threshold: 0.8 # 提高阈值减少误报 + + security: + autonomy: + loop-interval-seconds: 60 # 增大间隔降低 CPU 占用 + max-actions-per-hour: 5 # 限制自动操作频率 +``` + +### 大型服务器推荐配置(100+ 玩家) + +```yaml +serverguard: + monitor: + tps-threshold: 18 # 更严格的 TPS 阈值 + connection-threshold: 200 # 更高的连接阈值 + + security: + minecraft-defense: + login-burst-threshold: 30 # 允许更高的登录突发 + bot-swarm-threshold: 30 + ddos-defense: + syn-flood-threshold: 300 + minecraft-status-threshold: 50 + + ai: + sliding-window-size: 200 # 更大的分析窗口 + deepseek: + analysis-interval-seconds: 120 # 降低分析频率 + + self-healing: + tps-emergency-threshold: 15 # 更早触发自动恢复 +``` + +### 小型服务器推荐配置(< 20 玩家) + +```yaml +serverguard: + monitor: + tps-threshold: 12 + cpu-threshold: 90.0 + + ai: + use-prediction: false # 关闭预测功能节省资源 + sliding-window-size: 50 + + security: + super-evolution: + # 低资源消耗模块全部启用 + anti-kill-aura: true + anti-reach: true + anti-speed: true + anti-fly: true + anti-xray: true + # ... 按需开启 ``` --- ## 常见问题 -### Q: 如何查看AI是否正常工作? -```bash -aluer> ask 你好 -``` -如果返回AI回答,说明配置正确。 +### Q1: Plugin 模式和 External 模式如何选择? -### Q: 收不到邮件预警怎么办? -1. 检查 `application.yml` 中的邮箱配置 -2. 确保使用的是授权码而非登录密码 -3. 检查垃圾邮件文件夹 +**A**: 如果服务器的 PaperMC 版本 >= 1.21.1 且你可以安装插件,强烈推荐 Plugin 模式。Plugin 模式延迟 < 1ms,能够获取完整的 Bukkit 事件数据,检测精度和实时性远超 External 模式。External 模式适用于你无法安装插件或仅需要基础监控的场景。 -### Q: 如何完全停止系统? -```bash -sudo systemctl stop aluer -``` +### Q2: DeepSeek API 是必需的吗? -### Q: 如何查看运行日志? -```bash -# Systemd 日志 -sudo journalctl -u aluer -f +**A**: 不是必需的,但强烈推荐。没有 DeepSeek,AI 自主分析和自动防御功能将不可用,但所有 135+ 安全模块仍然正常工作。你可以在 `ai.deepseek.enabled: false` 关闭。 -# 应用日志 -tail -f logs/aluer.log -``` +### Q3: 如何只启用反作弊功能? -### Q: AI防御模式有什么用? -AI防御模式开启后,系统会自动: -- 分析日志中的威胁 -- 检测异常流量 -- 预测服务器问题 -- 自动执行防御动作 +**A**: 在 `application.yml` 的 `super-evolution` 节中,将不需要的模块开关设置为 `false`,仅保留 `anti-*` 相关的反作弊开关。 -### Q: 如何更新系统? -```bash -# 停止服务 -sudo systemctl stop aluer +### Q4: 误封了玩家怎么办? -# 备份数据 -cp -r /opt/aluer/backups /backup/ +**A**: +1. 使用 `unban ` 命令立即解封 +2. 使用 `ai analyze ` 查看 AI 分析结果 +3. 调整对应模块的检测阈值或暂时禁用 +4. 确保 `self-healing.dry-run: true` 在测试阶段启用(干燥运行不会实际执行封锁) -# 替换jar包 -cp target/AluerServerGuard-V4.0.jar /opt/aluer/ +### Q5: 系统对服务器性能影响有多大? -# 重启服务 -sudo systemctl start aluer -``` +**A**: 在 Plugin 模式下,插件部分内存占用约 50MB,外部引擎约 200MB。在 50 人服务器上,CPU 额外开销约 5-10%。External 模式下对 Minecraft 进程零影响,但检测能力有限。 + +### Q6: 如何更新到最新版本? + +**A**: +1. 备份当前配置 `cp application.yml application.yml.bak` +2. 拉取最新代码 `git pull` +3. 重新编译 `./apache-maven-3.9.6/bin/mvn package -DskipTests` +4. 重新部署 JAR +5. 对比新旧 `application.yml` 合并新增配置项 + +### Q7: 日志文件在哪里? + +**A**: +- ServerGuard 引擎日志:`/var/log/serverguard.log`(可在 `logging.file.name` 配置) +- Minecraft 服务器日志:`/opt/minecraft/logs/latest.log` +- 告警报告:`./reports/`(可在 `serverguard.report.dir` 配置) + +### Q8: 支持哪些 Minecraft 版本? + +**A**: 当前基于 PaperMC API 1.21.1-R0.1-SNAPSHOT,理论上兼容 PaperMC 1.21.x 全系列。其他版本需要调整 API 依赖。 --- ## 技术支持 -- 问题反馈: https://github.com/ZpjDev/Aluer/issues -- 文档更新: https://docs.aluer.com - ---- - -*Aluer v1.0.0 - 保护您的 Minecraft 服务器* +- 项目文档:`docs/` 目录 +- 开发规范:`CLAUDE.md` +- 项目结构:`README.md` +- API 协议:见 `AgentMessage.java` 源码注释