Hussain648568/Secure-Static-Malware-Platform

GitHub: Hussain648568/Secure-Static-Malware-Platform

一个采用安全优先设计原则构建的全栈静态恶意软件检测平台,结合随机森林机器学习与 SHAP 可解释 AI 对 PE 文件进行威胁分析。

Stars: 0 | Forks: 0

# SecureMalwarePlatform **一个采用安全优先设计原则构建的全栈恶意软件分析平台。** 通过机器学习进行静态 PE 分析 · 可解释 AI (SHAP) · VirusTotal 威胁情报 · AES-256 加密 · JWT + MFA 身份验证 [![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://www.python.org/) [![Flask](https://img.shields.io/badge/Flask-2.x-000000?style=for-the-badge&logo=flask&logoColor=white)](https://flask.palletsprojects.com/) [![Docker](https://img.shields.io/badge/Docker-Containerized-2496ED?style=for-the-badge&logo=docker&logoColor=white)](https://www.docker.com/) [![MySQL](https://img.shields.io/badge/MySQL-Database-4479A1?style=for-the-badge&logo=mysql&logoColor=white)](https://www.mysql.com/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)](LICENSE) [![Security: Bandit](https://img.shields.io/badge/Security-Bandit%20Scanned-green?style=for-the-badge)](https://bandit.readthedocs.io/)
## 目录 - [概述](#-overview) - [系统架构](#-system-architecture) - [安全功能](#-security-features) - [技术栈](#-tech-stack) - [项目结构](#-project-structure) - [前置条件](#-prerequisites) - [设置与安装](#-setup--installation) - [运行平台](#-running-the-platform) - [API 参考](#-api-reference) - [安全文档](#-security-documentation) - [生成安全报告](#-generating-security-reports) ## 概述 **SecureMalwarePlatform** 是一个用于分析潜在恶意 Windows 可执行文件(`.exe` 文件)的多页 Web 应用程序。它是作为一个**安全软件设计**项目构建的,主要目标是在全栈应用程序中展示真实的安全编码实践。 该平台实现了一个**分流 pipeline**:当上传可执行文件时,首先会与 VirusTotal 全球威胁数据库进行比对。如果哈希值未知(潜在的 zero-day),该文件将被转发到运行随机森林 ML 分类器的**隔离 Docker container** 中。模型输出威胁概率评分,并使用 **SHAP (SHapley Additive exPlanations)** 生成人类可读的解释,说明是哪些 PE header 特征驱动了该预测——所有这些最终都将汇编成一份加密的 PDF 报告。 ## 系统架构 ``` ┌─────────────────────────────────────────┐ │ USER'S BROWSER │ └───────────────────┬─────────────────────┘ │ HTTPS (Port 443) ┌───────────────────▼─────────────────────┐ │ CADDY REVERSE PROXY │ │ (TLS Termination + HSTS Header) │ └───────────────────┬─────────────────────┘ │ HTTP (Port 5000) ┌───────────────────▼─────────────────────┐ │ FLASK BACKEND │ │ ┌─────────────┐ ┌──────────────────┐ │ │ │ Auth Routes │ │ Upload Routes │ │ │ │ /api/auth │ │ /api/upload │ │ │ └─────────────┘ └──────────────────┘ │ │ │ │ │ │ ┌──────▼──────┐ ┌───────▼────────┐ │ │ │ MySQL DB │ │ VirusTotal API │ │ │ │ (Users + │ │ (Ext. Threat │ │ │ │ Reports) │ │ Intelligence) │ │ │ └─────────────┘ └────────────────┘ │ │ │ │ │ ┌──────▼───────────────────────────┐ │ │ │ DOCKER ML CONTAINER (Port 5001) │ │ │ │ Bound to 127.0.0.1 only │ │ │ │ ┌──────────────────────────┐ │ │ │ │ │ Random Forest Classifier │ │ │ │ │ │ + SHAP XAI Explainer │ │ │ │ │ │ + PE Header Parser │ │ │ │ │ └──────────────────────────┘ │ │ │ └───────────────────────────────────┘ │ └─────────────────────────────────────────┘ ``` ### 分析分流 Pipeline ``` Upload .exe │ ├── [Validation] Extension check → Magic bytes (MZ) check → SHA-256 integrity check │ ▼ VirusTotal Hash Lookup │ ├── Known Malware ──────────────────────────────► Generate VT Report (Encrypted PDF) │ └── Unknown / Not Found │ ▼ ML Container (Docker) │ ├── Parse PE Headers (50+ features) ├── Random Forest Prediction → Malware Score % ├── SHAP Explainability → Top Contributing Factors │ ▼ Generate ML Report (Encrypted PDF) │ ▼ File bytes discarded from memory — NOT persisted to disk ``` ## 安全功能 | 功能 | 实现 | 位置 | |---|---|---| | **Container 化的 ML 执行** | PE 解析与 ML 推理在 Docker 中隔离;`pefile` 中的漏洞无法触及主应用 | `ml_container/` + `docker-compose.yml` | | **基于角色的访问控制 (RBAC)** | `user` 和 `admin` 角色作为 JWT claims 嵌入;`@token_required` 和 `@admin_required` 装饰器强制执行访问权限 | `src/routes/upload_routes.py` | | **多因素身份验证 (MFA)** | 所有用户登录都需要通过 `pyotp` 进行 TOTP 验证;MFA 密钥在静态下使用 AES-256 加密 | `src/routes/auth_routes.py`, `src/services/auth_service.py` | | **防篡改审计日志** | 仅追加的加密日志;每个条目都经过 SHA-256 哈希处理并与前一个条目链接——任何删除或修改都是可检测的 | `src/services/logger.py` | | **静态 AES-256 加密** | 所有 PDF 报告和 MFA 密钥在存储到磁盘之前都使用 Fernet (AES-256-CBC) 进行加密 | `src/services/report_service.py`, `src/services/auth_service.py` | | **传输中的 TLS** | Caddy 分配本地 TLS 证书并强制执行 HTTPS;HSTS header 防止降级攻击 | `Caddyfile`, `app.py` | | **暴力破解防护** | 5 次失败尝试 → 账户锁定 15 分钟;计数器设有上限,以防止在持续攻击下发生整数溢出 | `src/routes/auth_routes.py` | | **速率限制** | 全局:200次/天,50次/小时。登录:10次/分钟。注册:5次/分钟 | `app.py` | | **内存文件处理** | 恶意软件样本永远不会写入磁盘;完全在内存中解析和分析,然后被丢弃 | `src/routes/upload_routes.py`, `ml_container/app.py` | | **传输完整性验证** | 客户端在上传前计算 SHA-256 哈希;服务器重新计算并拒绝不匹配项 | `src/routes/upload_routes.py`, `src/services/file_service.py` | | **防止文件伪造** | 扩展名白名单 (`.exe`) + magic byte (`MZ`) 验证以检测重命名的文件 | `src/services/file_service.py` | | **防止 SQL 注入** | 所有数据库交互均使用参数化查询——零字符串格式化的 SQL | 所有路由文件 | | **防止 XSS** | 动态内容通过 `textContent`(而非 `innerHTML`)渲染;严格的 Content-Security-Policy header | `app.py`, `src/templates/` | | **防止路径遍历** | 所有文件哈希 URL 参数在用于文件系统之前,均根据严格的 `^[a-fA-F0-9]{64}$` 正则表达式进行验证 | `src/routes/upload_routes.py` | | **安全 Header** | CSP, HSTS, X-Frame-Options (DENY), X-Content-Type-Options, Referrer-Policy, Permissions-Policy | `app.py` | | **安全失败启动** | 如果缺少 `JWT_SECRET` 或 `AES_ENCRYPTION_KEY`,应用程序在启动时会立即崩溃 | `src/services/auth_service.py`, `src/services/file_service.py` | | **通用错误消息** | 身份验证失败返回相同的消息以防止用户枚举;`debug=False` 防止堆栈跟踪泄露 | `src/routes/auth_routes.py`, `app.py` | ## 技术栈 ### 主应用程序 | 组件 | 技术 | |---|---| | 后端框架 | Flask | | 身份验证 | JWT (`PyJWT`) + TOTP MFA (`pyotp`) | | 密码哈希 | `bcrypt` | | 加密 | `cryptography` (Fernet / AES-256) | | 速率限制 | `flask-limiter` | | 数据库 | MySQL (`mysql-connector-python`) | | PDF 生成 | `fpdf2` | | 反向代理 / TLS | Caddy | ### ML Container | 组件 | 技术 | |---|---| | PE Header 解析 | `pefile` | | ML 模型 | 随机森林 (`scikit-learn`) | | 可解释 AI | SHAP (`shap`) | | 数据处理 | `pandas`, `numpy` | | API | Flask (内部微服务) | ## 项目结构 ``` SecureMalwarePlatform/ ├── app.py # Flask app entry point, security headers, rate limiting ├── Caddyfile # Caddy reverse proxy configuration (HTTPS) ├── docker-compose.yml # ML container orchestration ├── requirements.txt # Main app Python dependencies ├── .env.example # Environment variable template (copy to .env) ├── LICENSE ├── CONTRIBUTING.md │ ├── database/ │ └── schema.sql # MySQL schema — run once to initialize DB │ ├── ml_container/ # Isolated Docker ML microservice │ ├── Dockerfile # Non-root user, minimal base image │ ├── app.py # PE parser + Random Forest + SHAP endpoint │ ├── requirements.txt │ └── small_malware_model.pkl # Pre-trained Random Forest model bundle │ ├── src/ │ ├── routes/ │ │ ├── auth_routes.py # Register, login, account lockout │ │ └── upload_routes.py # File upload, reports, admin endpoints │ │ │ ├── services/ │ │ ├── auth_service.py # bcrypt, JWT, MFA (pyotp), AES encryption │ │ ├── file_service.py # Magic byte validation, SHA-256 hashing │ │ ├── ml_service.py # HTTP client to ML Docker container │ │ ├── report_service.py # Encrypted PDF report generation │ │ ├── vt_service.py # VirusTotal API integration │ │ └── logger.py # Encrypted, hash-chained audit logger │ │ │ ├── templates/ │ │ ├── login.html # Login page │ │ ├── register.html # Registration + MFA QR setup │ │ ├── dashboard.html # User dashboard │ │ └── admin.html # Admin panel (users, reports, logs) │ │ │ ├── logs/ # (gitignored) Encrypted audit logs at runtime │ ├── reports/ # (gitignored) Encrypted PDF reports at runtime │ └── temp_store/ # (gitignored) Temporary file buffer │ └── Security Features Documentation/ ├── SECURITY_AUDIT.md # Secure coding principles implementation guide ├── API_SECURITY_AUDIT.md # API security implementation guide └── CODE_QUALITY_AUDIT.md # Static analysis (Bandit) findings summary ``` ## 前置条件 在运行该平台之前,请确保您的系统已安装以下内容: | 依赖 | 用途 | 下载 | |---|---|---| | **Python 3.10+** | 核心 runtime | [python.org](https://www.python.org/downloads/) | | **Docker Desktop** | ML container 执行 | [docker.com](https://www.docker.com/products/docker-desktop/) | | **MySQL Server 8.0+** | 用户和报告数据 | [mysql.com](https://dev.mysql.com/downloads/mysql/) | | **Caddy** | HTTPS / TLS 终止 | [caddyserver.com](https://caddyserver.com/docs/install) | ## 设置与安装 ### 1. 克隆代码库 ``` git clone https://github.com/your-username/SecureMalwarePlatform.git cd SecureMalwarePlatform ``` ### 2. 初始化数据库 登录 MySQL 并运行 schema 脚本: ``` mysql -u root -p < database/schema.sql ``` 这将创建包含 `users` 和 `user_reports` 表的 `malware_platform` 数据库。 ### 3. 配置环境变量 复制示例文件并填写您的值: ``` cp .env.example .env ``` 打开 `.env` 并填充每个变量。请特别注意: - **`JWT_SECRET`** — 生成命令:`python -c "import secrets; print(secrets.token_hex(32))"` - **`AES_ENCRYPTION_KEY`** — 生成命令:`python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"` - **`ADMIN_PASSWORD_HASH`** — 生成命令:`python -c "import bcrypt; print(bcrypt.hashpw(b'YourPassword', bcrypt.gensalt()).decode())"` - **`VT_API_KEY`** — 来自 [virustotal.com](https://www.virustotal.com/) 的免费 API 密钥 ### 4. 设置 Python 虚拟环境 ``` python -m venv venv # Windows .\venv\Scripts\activate # macOS / Linux source venv/bin/activate pip install -r requirements.txt ``` ## 运行平台 该平台需要**三个并发进程**。请打开三个独立的终端窗口。 ### 终端 1 — 启动 ML Docker Container ``` docker-compose up -d --build ``` ### 终端 2 — 启动 Flask 后端 ``` # 首先激活 venv .\venv\Scripts\activate # Windows source venv/bin/activate # macOS / Linux python app.py ``` ### 终端 3 — 启动 Caddy 反向代理 ``` caddy run ``` ### 访问平台 打开浏览器并导航至: ``` https://localhost ``` ## API 参考 ### 身份验证端点 (`/api/auth`) | 方法 | 端点 | 权限 | 描述 | |---|---|---|---| | `GET` | `/api/auth/register-page` | 无 | 提供注册 HTML 页面 | | `GET` | `/api/auth/login-page` | 无 | 提供登录 HTML 页面 | | `POST` | `/api/auth/register` | 无 | 注册新用户;返回 MFA 配置 URI | | `POST` | `/api/auth/login` | 无 | 验证用户/管理员身份;返回签名的 JWT | ### 上传与报告端点 (`/api/upload`) | 方法 | 端点 | 权限 | 描述 | |---|---|---|---| | `GET` | `/api/upload/dashboard` | 无(在客户端检查 JWT) | 提供用户控制面板 | | `GET` | `/api/upload/verify-session` | `Bearer ` | 验证 JWT 并返回用户身份 + 角色 | | `POST` | `/api/upload/file` | `Bearer ` | 上传 `.exe` 进行分析;运行分流 pipeline | | `GET` | `/api/upload/my-reports` | `Bearer ` | 列出已认证用户的报告 | | `GET` | `/api/upload/report/` | `Bearer ` | 下载已解密的 PDF 报告(强制所有权验证) | ### 管理员端点 (`/api/upload/admin`) — 需要 `role: admin` | 方法 | 端点 | 权限 | 描述 | |---|---|---|---| | `GET` | `/api/upload/admin/dashboard` | 管理员 JWT | 提供管理员控制面板 | | `GET` | `/api/upload/admin/users` | 管理员 JWT | 列出所有已注册的用户及其报告数量 | | `GET` | `/api/upload/admin/user//reports` | 管理员 JWT | 列出特定用户的所有报告 | | `DELETE` | `/api/upload/admin/user/` | 管理员 JWT | 级联删除:用户 + 所有报告 + 加密文件 | | `GET` | `/api/upload/admin/logs` | 管理员 JWT | 检索已解密并经过完整性验证的审计日志链 | ### 内部 ML Container API (`http://127.0.0.1:5001`) — 不公开访问 | 方法 | 端点 | 描述 | |---|---|---| | `POST` | `/analyze` | 接收原始 `.exe` 字节;返回 RF 预测 + SHAP 解释 JSON | ## 安全文档 本项目实现的每项安全编码原则的详细文档可在 [`Security Features Documentation/`](Security%20Features%20Documentation/) 目录中找到: | 文档 | 描述 | |---|---| | [`SECURITY_AUDIT.md`](Security%20Features%20Documentation/SECURITY_AUDIT.md) | 将每项安全编码原则(输入验证、身份验证、RBAC、错误处理、数据保护、注入防护)映射到特定的文件和函数 | | [`API_SECURITY_AUDIT.md`](Security%20Features%20Documentation/API_SECURITY_AUDIT.md) | 完整的 API 清单,包含每个端点的安全控制(JWT、速率限制、HTTPS、token 过期处理) | | [`CODE_QUALITY_AUDIT.md`](Security%20Features%20Documentation/CODE_QUALITY_AUDIT.md) | Bandit 扫描器的静态分析结果,包含严重性摘要和修复说明 | ## 生成安全报告 Bandit 安全扫描结果未提交到代码库中(它们是生成的制品)。要在本地重新生成它们: ``` # 首先激活您的虚拟环境 pip install bandit # 生成 HTML 报告 bandit -r . --exclude ./venv,./ml_container -f html -o bandit_report.html # 生成 JSON 报告 bandit -r . --exclude ./venv,./ml_container -f json -o bandit_report.json # 终端中的快速文本摘要 bandit -r . --exclude ./venv,./ml_container ```
标签:Apex, DNS 反向解析, Docker, Flask, 云安全监控, 可解释AI, 安全工程, 安全防御评估, 机器学习, 网络信息收集, 请求拦截, 逆向工具, 静态分析