crastatelvin/sentinel-ai

GitHub: crastatelvin/sentinel-ai

一个基于AI驱动的实时威胁情报日志分析平台,解决日志关联检测、攻击溯源与响应剧本生成问题。

Stars: 0 | Forks: 0

# 🛡️ SENTINEL AI ### 实时 AI 驱动的威胁情报与日志分析平台 [![Python](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://www.python.org/) [![FastAPI](https://img.shields.io/badge/FastAPI-Latest-009688?style=for-the-badge&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/) [![React](https://img.shields.io/badge/React-19.x-61DAFB?style=for-the-badge&logo=react&logoColor=black)](https://react.dev/) [![Vite](https://img.shields.io/badge/Vite-8.x-646CFF?style=for-the-badge&logo=vite&logoColor=white)](https://vitejs.dev/) [![Gemini](https://img.shields.io/badge/Google_Gemini-Flash-4285F4?style=for-the-badge&logo=google&logoColor=white)](https://ai.google.dev/) [![SQLite](https://img.shields.io/badge/SQLite-Database-003B57?style=for-the-badge&logo=sqlite&logoColor=white)](https://www.sqlite.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-green?style=for-the-badge)](LICENSE)

![7 Threat Categories](https://img.shields.io/badge/7_Attack_Categories-Detected-red?style=for-the-badge) ![WebSocket Live Feed](https://img.shields.io/badge/WebSocket-Live_Feed-00d4ff?style=for-the-badge) ![Gemini AI](https://img.shields.io/badge/Gemini_AI-Briefing_%26_Playbook-orange?style=for-the-badge) ![3D Globe](https://img.shields.io/badge/3D_Globe-IP_Geolocation-brightgreen?style=for-the-badge)
## 📋 目录 - [Overview](#-overview) - [Features](#-features) - [Architecture](#-architecture) - [Tech Stack](#-tech-stack) - [Threat Detection Engine](#-threat-detection-engine) - [AI Analysis Pipeline](#-ai-analysis-pipeline) - [Dashboard Components](#-dashboard-components) - [Database Models](#-database-models) - [Project Structure](#-project-structure) - [Installation](#-installation) - [Usage](#-usage) - [WebSocket Live Feed](#-websocket-live-feed) - [Sample Logs](#-sample-logs) - [Configuration](#-configuration) - [Security Notes](#-security-notes) - [Contributing](#-contributing) ## 🧠 概述 SENTINEL AI 模拟一个实时安全运营中心(SOC),任何开发者或安全研究人员都可以在本地运行。系统摄取原始服务器日志文件并运行多阶段自动化分析流水线: 1. **日志解析** — 通过正则表达式自动检测 Apache、Nginx 和 Auth 日志格式 2. **威胁检测** — 使用正则匹配扫描每条日志条目,检测 7 种威胁模式库 3. **IP 地理定位** — 通过 `ip-api.com` API 并发地理定位所有唯一攻击者 IP 4. **攻击链重建** — 按源 IP 分组威胁并识别升级模式(例如:侦察 → 暴力破解 → RCE) 5. **预测性告警** — 基于检测到的类别组合进行规则驱动的下一次攻击预测 6. **Gemini AI 深度分析** — 生成包含四个部分的结构化安全报告:执行简报、攻击叙事、风险评估,以及包含确切终端命令的 5 步修复剧本 在此流水线中,每一步都会通过 **WebSocket** 将实时状态更新广播到前端,创建真实的 SOC 终端体验。 ## 🖥️ 应用预览

{50A49800-CEEF-4A57-ACD3-8FFB78680AFE}

{73392775-6AF4-46AE-BC2F-C450998BA59F}

{D9C28621-1A5C-4CC9-8514-8A50633166A6}

{68634D08-EEA5-468C-B8D6-943D1FFD1B9D}

{440F9229-34A9-4364-A768-8B502D624109}

{58268628-590B-4DBD-B8BC-2C14E3AB6655}

{4F9E6B07-CE88-4747-BCB7-38B400D9B790}

## ✨ 功能 | Feature | Description | |---|---| | 🔍 **7-Category Threat Detection** | 暴力破解、SQL 注入、XSS、路径遍历、侦察、命令注入、DDoS — 全部通过正则模式匹配实现 | | 🌍 **3D Attack Globe** | `react-globe.gl` 渲染夜间模式地球,地理定位的攻击源点按攻击次数缩放并按严重性着色 | | ⛓ **Attack Chain Analysis** | 为每个 IP 重构多阶段攻击序列 — 识别侦察→暴力破解、暴力破解→RCE 以及多向量 APT 模式 | | 🧠 **Gemini AI Briefing** | 4 部分 AI 报告:执行摘要 · 攻击叙事 · 风险评估 · 修复剧本(含终端命令) | | 🛡️ **Remediation Playbook** | AI 生成的 5 步操作计划,每条命令支持一键复制到剪贴板 | | ◎ **Threat Radar** | Recharts `RadarChart` 同时可视化所有 7 类攻击量 | | ⟳ **Attack Timeline** | Recharts `AreaChart` 显示日志时间窗口内总威胁与关键威胁密度随时间的变化 | | ▶ **Live Terminal Feed** | 滚动终端风格威胁日志,按严重性着色(JetBrains Mono 字体) | | 📡 **WebSocket Status Bar** | 前后端实时推送流水线进度 | | 🔐 **JWT Auth System** | bcrypt 密码哈希 + python-jose JWT 令牌(24 小时过期) | | 🗃️ **SQLite Persistence** | SQLAlchemy ORM 模型用于用户、威胁和分析记录 | | 📊 **Threat Intelligence Table** | 分页表格,包含严重性徽章、置信度进度条、国家和描述 | ## 🏗️ 架构 ``` ┌──────────────────────────────────────────────────────────────┐ │ Browser / React + Vite App │ │ │ │ ┌────────────┐ ┌────────────────────────────────────────┐ │ │ │ UploadPage │ │ DashboardPage │ │ │ │ drag-drop │ │ StatusBar (WebSocket live messages) │ │ │ │ log upload │ │ │ │ │ └─────┬──────┘ │ ThreatCounter │ GlobeMap │ ThreatRadar│ │ │ │ │ TerminalFeed │ TimelineChart │ │ │ │ │ ThreatTable │ │ │ │ │ AIBriefing │ RemediationPanel │ │ │ │ │ AttackChain │ │ │ │ └────────────────────────────────────────┘ │ └────────┼──────────────────────────┬──────────────────────────┘ │ POST /upload │ WebSocket /ws │ GET /threats │ (live pipeline events) │ GET /chains │ │ GET /ai-analysis │ │ GET /map-data │ ┌────────▼──────────────────────────▼───────────────────────────┐ │ FastAPI Backend (main.py) │ │ │ │ ┌─────────────────┐ ┌──────────────────────────────────┐ │ │ │ log_parser.py │ │ threat_detector.py │ │ │ │ Auto-detect: │ │ 7 pattern libs · regex match │ │ │ │ Apache/Nginx/ │ │ Severity scoring · confidence │ │ │ │ Auth/CSV │ └──────────────────────────────────┘ │ │ └─────────────────┘ │ │ │ │ ┌──────────────────────┐ ┌───────────────────────────┐ │ │ │ threat_enricher.py │ │ attack_chain.py │ │ │ │ httpx async geo- │ │ Group by IP · detect │ │ │ │ location · ip-api │ │ escalation patterns │ │ │ └──────────────────────┘ └───────────────────────────┘ │ │ │ │ ┌───────────────────────────────────────────────────────┐ │ │ │ gemini_service.py │ │ │ │ analyze_threats() → 4-section structured report │ │ │ │ predict_next_attack() → rule-based prediction │ │ │ │ parse_ai_response() → structured dict parser │ │ │ └───────────────────────────────────────────────────────┘ │ │ │ │ ┌────────────────┐ ┌──────────────┐ ┌────────────────┐ │ │ │ models.py │ │ auth.py │ │ database.py │ │ │ │ User/Threat/ │ │ JWT · bcrypt│ │ SQLite via │ │ │ │ Analysis ORM │ │ OAuth2 │ │ SQLAlchemy │ │ │ └───────┬────────┘ └──────────────┘ └───────┬────────┘ │ │ └──────────── SQLAlchemy ORM ──────────┘ │ │ sentinel.db │ └────────────────────────────────────────────────────────────── ┘ ``` ## 🛠️ 技术栈 | Layer | Technology | |---|---| | **Frontend** | React 19, Vite 8, Tailwind CSS 4, Framer Motion, Recharts, react-globe.gl, react-markdown, Axios | | **Backend** | FastAPI, Uvicorn, Python 3.11+ | | **AI / LLM** | Google Gemini Flash (`gemini-flash-latest`) via `google-genai` SDK | | **Database** | SQLite via SQLAlchemy ORM | | **Auth** | python-jose (JWT), passlib (bcrypt), OAuth2PasswordBearer | | **Geolocation** | ip-api.com 通过异步 `httpx` | | **Real-time** | WebSocket(FastAPI 原生 + 浏览器 WebSocket API) | | **Log Formats** | Apache 组合日志、Nginx 访问日志、Linux Auth/syslog、CSV | ## 🔬 威胁检测引擎 `threat_detector.py` 对每条解析后的日志条目扫描 7 个威胁类别,每个类别包含多个正则模式。 | Category | Severity | Patterns Detected | |---|---|---| | **Brute Force** | 🔴 Critical | `Failed password`, `authentication failure`, `BREAK-IN ATTEMPT`, `Invalid user` | | **SQL Injection** | 🔴 Critical | `UNION SELECT`, `OR 1=1`, `DROP TABLE`, `sleep()`, `benchmark()` | | **Command Injection** | 🔴 Critical | `;ls`, `\|whoami`, `$(...)`, `/bin/bash`, `netcat` | | **XSS Attack** | 🟠 High | ` dict: # Sends: threat count, severity breakdown, category breakdown, # top 5 attacking IPs, and 30-threat detail list # Returns parsed dict with 4 keys: return { "executive_briefing": "...", # 3-sentence incident report (Markdown) "attack_narrative": "...", # 4-5 sentence attacker story (Markdown) "risk_assessment": "...", # CRITICAL/HIGH/MEDIUM/LOW rating + rationale "remediation_playbook": [ # 5 actions, each with ACTION + COMMAND {"action": "Block IPs", "command": "ufw deny from 45.33.32.156"}, ... ] } ``` `predict_next_attack()` 基于检测到的类别组合运行规则驱动的预测 — 如果存在 `recon` 但缺少 `brute_force`,则警告即将进入登录攻击阶段;如果同时发现 `brute_force` + `cmdi`,则升级为系统警告。 ## 🖥️ 仪表板组件 | Component | Description | |---|---| | `StatusBar` | 顶部导航栏显示实时 WebSocket 消息、威胁计数和连接状态圆点 | | `ThreatCounter` | 大号 Orbitron 字体威胁总数,带严重性分解动画(Critical/High/Medium/Low) | | `GlobeMap` | 懒加载的 `react-globe.gl` 3D 地球,威胁点按数量缩放、按严重性着色 | | `ThreatRadar` | Recharts `RadarChart` 映射所有 7 类别的攻击量 | | `TerminalFeed` | 自动滚动的终端风格日志,按严重性着色边框(JetBrains Mono) | | `TimelineChart` | Recharts 双区域图:总威胁与关键威胁随时间的变化 | | `ThreatTable` | 分页表格 — 严重性徽章、威胁类型、源 IP、国家、置信度进度条、描述 | | `AIBriefing` | 4 部分 Gemini 分析,使用 `react-markdown` 渲染:简报 · 叙事 · 风险 · 预测 | | `RemediationPanel` | 带一键复制按钮的编号操作列表(每条命令附带深色终端块) | | `AttackChain` | 前 5 条按 IP 的攻击链,含技术标签、叙事文本、攻击计数和严重性边框 | ## 🗃️ 数据库模型 ### `User` | Field | Type | Description | |---|---|---| | `id` | Integer (PK) | 自增 ID | | `username` | String (unique) | 登录标识符 | | `hashed_password` | String | bcrypt 哈希密码 | ### `Threat` | Field | Type | Description | |---|---|---| | `id` | Integer (PK) | 威胁记录 ID | | `ip` | String | 源攻击者 IP | | `time` | String | 日志条目时间戳 | | `method` / `path` | String | HTTP 方法和请求路径 | | `threat_name` | String | 例如 `SQL Injection`, `Brute Force` | | `category` | String | 例如 `sqli`, `brute_force`, `recon` | | `severity` | String | `critical`, `high`, `medium`, `low` | | `confidence` | Float | 检测置信度分数 | | `country` / `lat` / `lng` | String/Float | 地理定位数据(来自 ip-api.com) | | `timestamp` | DateTime | 记录创建时间(UTC) | ### `Analysis` | Field | Type | Description | |---|---|---| | `id` | Integer (PK) | 分析记录 ID | | `executive_briefing` | Text | Gemini 执行摘要部分 | | `attack_narrative` | Text | Gemini 攻击故事部分 | | `risk_assessment` | Text | Gemini 风险评级部分 | | `remediation_playbook` | Text | JSON 序列化的操作/命令对列表 | | `timestamp` | DateTime | 分析创建时间(UTC) | ## 📁 项目结构 ``` sentinel-ai/ │ ├── backend/ │ ├── main.py # FastAPI app — /upload, /threats, /chains, /ai-analysis, /map-data, /ws │ ├── log_parser.py # Auto-detect + parse Apache, Nginx, Auth, and CSV log formats │ ├── threat_detector.py # 7-category regex threat engine with severity scoring │ ├── threat_enricher.py # Async IP geolocation via ip-api.com (httpx) + globe map data │ ├── attack_chain.py # Group threats by IP, detect and label escalation chains │ ├── gemini_service.py # Gemini Flash integration — analyze_threats(), predict_next_attack() │ ├── auth.py # JWT creation/validation, bcrypt password hashing, OAuth2 scheme │ ├── database.py # SQLAlchemy engine + session factory (SQLite: sentinel.db) │ ├── models.py # ORM models: User, Threat, Analysis │ ├── requirements.txt # Python dependencies │ ├── .env # GEMINI_API_KEY — do not commit │ └── .env.example # Environment variable template │ ├── frontend/ │ ├── src/ │ │ ├── App.jsx # Root — toggles UploadPage ↔ DashboardPage │ │ ├── main.jsx # React DOM entry point │ │ ├── pages/ │ │ │ ├── UploadPage.jsx # Animated drag-drop log upload with Framer Motion │ │ │ └── DashboardPage.jsx # Full SOC dashboard — 5 responsive grid rows │ │ ├── components/ │ │ │ ├── StatusBar.jsx # Live WebSocket pipeline status + connection dot │ │ │ ├── ThreatCounter.jsx # Animated Orbitron threat total + severity cards │ │ │ ├── GlobeMap.jsx # Lazy-loaded react-globe.gl 3D attack origin map │ │ │ ├── ThreatRadar.jsx # Recharts RadarChart across 7 attack categories │ │ │ ├── TerminalFeed.jsx # Auto-scroll terminal threat log (last 80 entries) │ │ │ ├── TimelineChart.jsx # Recharts dual AreaChart — total vs. critical threats │ │ │ ├── ThreatTable.jsx # Paginated threat intel table (top 20) │ │ │ ├── AIBriefing.jsx # Gemini 4-section report with react-markdown │ │ │ ├── RemediationPanel.jsx # Copyable terminal command playbook │ │ │ └── AttackChain.jsx # Top 5 per-IP attack chain reconstruction cards │ │ ├── hooks/ │ │ │ └── useWebSocket.js # WebSocket hook — connects to /ws, buffers 50 messages │ │ ├── services/ │ │ │ └── api.js # Axios wrappers for all REST endpoints │ │ └── styles/ │ │ └── globals.css # Dark SOC theme — Orbitron + JetBrains Mono │ ├── package.json │ ├── vite.config.js │ └── tailwind.config.js │ └── sample_logs/ ├── sample_apache.log # 8-entry Apache log with SQLi, XSS, path traversal, recon ├── sample_auth.log # 10-entry SSH auth log with brute force + BREAK-IN ATTEMPT └── sample_nginx.log # 8-entry Nginx log with recon and repeated login attempts ``` ## 🚀 安装 ### 先决条件 - Python 3.11+ - Node.js 18+ - [Google Gemini API key](https://ai.google.dev/) ### 1. 克隆仓库 ``` git clone https://github.com/crastatelvin/sentinel-ai.git cd sentinel-ai ``` ### 2. 后端设置 ``` cd backend python -m venv venv # 激活虚拟环境 source venv/bin/activate # Linux / macOS venv\Scripts\activate # Windows pip install -r requirements.txt ``` ### 3. 配置环境 ``` cp .env.example .env # 编辑 .env — 设置 GEMINI_API_KEY=your_key_here ``` ### 4. 启动后端 ``` uvicorn main:app --reload ``` API + WebSocket 服务器运行在 `http://localhost:8000` ### 5. 前端设置 ``` cd ../frontend npm install npm run dev ``` 前端运行在 `http://localhost:5173` ## 💻 使用说明 ### 运行威胁分析 1. 在 `http://localhost:5173` 打开应用 2. 拖放任意示例日志文件或您自己的 Apache、Nginx 或 SSH 认证日志 3. 观察 **StatusBar** 通过 WebSocket 显示实时流水线事件,每个阶段完成后更新 4. 分析完成后,**Dashboard** 自动在所有 10 个面板中填充数据 ### 阅读仪表板 - **ThreatCounter** — 总威胁数,红色动画;按类别按严重性分解 - **GlobeMap** — 3D 地球,地理定位的攻击源点;大小 = 数量,颜色 = 严重性 - **ThreatRadar** — 雷达图,快速识别主要攻击向量 - **TerminalFeed** — 实时滚动的颜色编码日志,记录每个检测到的威胁 - **TimelineChart** — 面积图,显示攻击强度和关键事件随时间的峰值 - **ThreatTable** — 详细表格,包含置信度进度条和地理数据 - **AIBriefing** — Gemini 的完整 4 部分 Markdown 报告,带预测告警 - **RemediationPanel** — 点击任意行的 **COPY** 复制精确的终端命令 - **AttackChain** — 每个 IP 的升级叙事(侦察→暴力破解、暴力破解→RCE、多向量 APT) ### 上传新文件 点击仪表板底部的 **↩ UPLOAD NEW LOG** 重置并分析新文件。 ## 📡 WebSocket 实时推送 后端在整个分析流水线中向所有连接的客户端广播实时状态事件。 ``` // frontend/src/hooks/useWebSocket.js const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8000/ws'; // Each broadcast has shape: { event: string, message: string } // Pipeline events in order: // "parsing" → "parsed" → "detected" → "enriched" → "analyzing" → "complete" ``` `StatusBar` 组件订阅此 Hook,并通过 `framer-motion` 将每条新消息动画到导航栏中心。Hook 在状态中缓冲最后 50 条消息,并跟踪 `connected` / `disconnected` / `error` 套接字状态。 ## 📂 示例日志 提供了三个开箱即用的日志文件用于即时测试: | File | Format | Threats Demonstrated | |---|---|---| | `sample_auth.log` | Linux SSH / syslog | 暴力破解、无效用户、BREAK-IN ATTEMPT(来自 4 个源 IP) | | `sample_apache.log` | Apache 组合日志 | SQL 注入、XSS、路径遍历(`/etc/passwd`)、侦察(`.git/`)、命令注入 | | `sample_nginx.log` | Nginx 访问日志 | 侦察(`wp-config.php`)、重复的 POST 登录尝试 | ## ⚙️ 配置 ``` # backend/.env GEMINI_API_KEY=your_gemini_api_key_here JWT_SECRET_KEY=your_secure_random_secret # Override the default ``` ``` # frontend/.env(创建此文件) VITE_API_URL=http://localhost:8000 VITE_WS_URL=ws://localhost:8000/ws ``` ## 🔒 安全注意事项 - 后端使用 `allow_origins=["*"]` — 在公开部署前请限制为前端来源 - 内存中的 `store` 字典是单个全局对象 — 不适用于多用户或并发会话;生产环境中请使用 Redis backed 会话存储 - `JWT_SECRET_KEY` 必须在部署前替换为加密安全的随机值 - `ip-api.com` 地理定位端点免费层限制为每分钟 45 次请求 — 避免过快上传非常大的日志文件 - 将 `.env` 添加到 `.gitignore` 以防止您的 Gemini API 密钥被提交 ## 📜 许可证 根据 **MIT License** 许可 — 详见 [LICENSE](LICENSE) 获取详细信息。
Made with ❤️ by [Crasta Telvin](https://github.com/crastatelvin) ⭐ Star this repo if you find it useful!
标签:AI安全, AI驱动安全, AMSI绕过, AV绕过, Chat Copilot, FastAPI, Gemini, masscan, Python, React, SEO: AI安全, SEO: 威胁检测, SEO: 实时监控, SEO: 网络安全, SQLite, Syscalls, TCP/IP协议栈, Vite, WebSockets, 修复剧本, 全球地理定位, 威胁情报平台, 威胁检测, 实时威胁情报, 攻击分类, 无后门, 日志上传, 网络安全平台, 逆向工具