Eniyalakshmi46/Data-Loss-Prevention-System-with-AI-Deduction

GitHub: Eniyalakshmi46/Data-Loss-Prevention-System-with-AI-Deduction

一款结合规则匹配与本地 LLM 语义分析的实时数据防泄漏系统,用于检测和告警文件中隐藏的敏感数据。

Stars: 0 | Forks: 0

# 智能 DLP 系统 一款适用于 Windows 的实时数据防泄漏系统,可检测隐藏在编码、加密或混淆文件中的敏感数据——将基于规则的检测与本地托管的 LLM 语义分析相结合。 ## 功能 | 层级 | 技术 | 可检测内容 | |---|---|---| | 文件监控 | watchdog (Windows) | 实时监控任何新增/修改的文件 | | 编码检测 | Regex + charset 分析 | Base64、Hex、URL 编码的 payload | | 加密检测 | Shannon 熵 | 加密 / 压缩文件 | | 模式匹配 | Regex + Luhn 算法 | 信用卡、SSN、API key、私钥、JWT | | 关键词扫描 | 字典查找 | 密码、机密术语、财务数据 | | 语义分析 | 通过 Ollama 的本地 LLM | 上下文感知的敏感数据理解 | | 告警 | 控制台 + 邮件 + 日志文件 | 实时多渠道通知 | ## 项目结构 ``` dlp_system/ ├── main.py ← Entry point (CLI) ├── config.py ← Loads settings from .env ├── requirements.txt ├── .env.example ← Copy to .env and fill in your values │ ├── core/ │ ├── analyzer.py ← Full pipeline orchestrator │ ├── monitor.py ← Real-time file system watcher │ ├── decoder.py ← Base64 / Hex / URL decode │ ├── entropy.py ← Shannon entropy (encryption detection) │ ├── pattern_matcher.py ← Regex patterns + Luhn algorithm │ └── llm_analyzer.py ← Ollama LLM semantic analysis │ ├── alerts/ │ ├── console_alert.py ← Color-coded terminal alerts │ └── email_alert.py ← SMTP email notifications │ ├── utils/ │ └── logger.py ← Rotating file logger (JSON structured) │ ├── logs/ ← Auto-created; dlp.log written here ├── quarantine/ ← Reserved for future quarantine feature └── tests/ └── test_dlp.py ← Unit tests (pytest) ``` ## 前置条件 ### Python 3.11+ ### 2. Ollama (本地 LLM) 从 https://ollama.com/download/windows 下载并安装。 然后拉取模型(任选其一): ``` ollama pull llama3 ollama pull mistral ollama pull gemma2 ollama pull phi3 ``` 启动 Ollama 服务器(安装后会自动在后台运行)。 ## 安装说明 ### 步骤 1 — 克隆或下载此项目 将 `dlp_system` 文件夹放在任意位置,例如 `C:\dlp_system`。 ### 步骤 2 — 在项目文件夹中打开命令提示符 ``` cd C:\dlp_system ``` ### 步骤 3 — 创建虚拟环境 ``` python -m venv venv venv\Scripts\activate ``` ### 步骤 4 — 安装依赖项 ``` pip install -r requirements.txt ``` ### 步骤 5 — 配置系统 ``` copy .env.example .env notepad .env ``` 填入你的值: ``` # 要监控的目录 WATCH_DIR=C:/Users/YourName/Desktop/monitored # Ollama model(必须与你拉取的相匹配) OLLAMA_MODEL=llama3 # 邮件警报 EMAIL_ENABLED=true SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your_email@gmail.com SMTP_PASS=your_gmail_app_password ALERT_RECIPIENT=security@yourcompany.com ``` ## 用法 ### 监控目录(实时) ``` python main.py ``` 使用你的 `.env` 中的 `WATCH_DIR`。 ``` python main.py --watch C:\Users\YourName\Documents\sensitive ``` 从命令行覆盖监控目录。 ``` python main.py --verbose ``` 还会为每个处理过的干净文件打印一行绿色的信息。 ### 扫描单个文件(单次) ``` python main.py --scan C:\path\to\suspicious_file.txt ``` 在终端打印完整的 JSON 报告。用于测试非常有用。 ## 运行测试 ``` pip install pytest python -m pytest tests/ -v ``` 预期输出: ``` tests/test_dlp.py::test_base64_detected PASSED tests/test_dlp.py::test_hex_detected PASSED tests/test_dlp.py::test_url_encoding_detected PASSED tests/test_dlp.py::test_clean_text_not_flagged PASSED tests/test_dlp.py::test_low_entropy_text PASSED tests/test_dlp.py::test_high_entropy_random PASSED tests/test_dlp.py::test_normal_text_entropy PASSED tests/test_dlp.py::test_luhn_valid_visa PASSED tests/test_dlp.py::test_luhn_valid_mastercard PASSED tests/test_dlp.py::test_luhn_invalid PASSED tests/test_dlp.py::test_detects_credit_card PASSED tests/test_dlp.py::test_detects_private_key PASSED tests/test_dlp.py::test_detects_aws_key PASSED tests/test_dlp.py::test_detects_keywords PASSED tests/test_dlp.py::test_clean_text_no_findings PASSED tests/test_dlp.py::test_false_positive_card_rejected PASSED ``` ## 手动测试系统 ### 测试 1 — Base64 编码的密码 在你的监控目录中创建一个文件: ``` import base64 payload = base64.b64encode(b"password=Admin@123&api_key=AKIAIOSFODNN7EXAMPLE").decode() with open("C:/Users/YourName/Desktop/monitored/test_b64.txt", "w") as f: f.write(payload * 3) ``` 预期:带有 `base64` 编码和 `aws_key` 模式的 **HIGH** 或 **CRITICAL** 告警。 ### 测试 2 — 纯文本信用卡 ``` echo Card number: 4532015112830366, CVV: 123, Expiry: 12/26 > monitored\test_card.txt ``` 预期:带有 `credit_card` 模式的 **MEDIUM** 或 **HIGH** 告警。 ### 测试 3 — 加密/高熵文件 ``` import os with open("C:/Users/YourName/Desktop/monitored/test_enc.bin", "wb") as f: f.write(os.urandom(8192)) ``` 预期:熵告警(suspicious = True,约 7.9 bits/byte)。 ### 测试 4 — Hex 编码的机密文档 ``` data = "CONFIDENTIAL: Project budget Q4 2025 = $4,200,000".encode().hex() with open("C:/Users/YourName/Desktop/monitored/test_hex.txt", "w") as f: f.write(data) ``` 预期:检测到 `hex` 编码 + `confidential` 关键词。 ## Pipeline 工作原理 ``` File created/modified │ ▼ [1] Read file bytes + text │ ▼ [2] Shannon entropy check entropy ≥ 7.2 → flag as possibly encrypted │ ▼ [3] Encoding detection Base64 / Hex / URL → decode hidden payloads │ ▼ [4] Pattern matching (rule-based) Credit cards (+ Luhn) / SSN / API keys / Private keys / JWT / Keywords │ ▼ [5] LLM semantic analysis (Ollama, local) Only triggered if risk_score > 0 or entropy suspicious │ ▼ [6] Threat verdict + severity scoring low / medium / high / critical │ ▼ [7] Alerts: Console + Email + Log file ``` ## 严重级别 | 严重性 | 触发条件 | |---|---| | **critical** | 风险评分 ≥ 60,或 LLM 置信度 > 80% | | **high** | 风险评分 ≥ 40,或 LLM 标记为敏感 | | **medium** | 风险评分 ≥ 20,或高熵文件 | | **low** | 未检测到威胁 | ## 日志文件格式 日志以结构化 JSON 行的形式写入 `logs/dlp.log`: ``` { "timestamp": "2025-03-21T14:32:10.123456", "file": "C:/monitored/report.txt", "severity": "high", "summary": "Encoded content detected (base64) | Sensitive patterns: credit_card, aws_key", "encoding_methods": ["base64"], "entropy": 4.21, "pattern_types": ["credit_card", "aws_key"], "keywords": ["confidential", "password"], "llm_sensitive": true, "llm_confidence": 0.91, "llm_categories": ["credentials", "financial_data"] } ``` ## 故障排除 | 问题 | 解决方案 | |---|---| | `ModuleNotFoundError: watchdog` | 在 venv 中运行 `pip install -r requirements.txt` | | `Ollama not reachable` | 启动 Ollama:在单独的终端中运行 `ollama serve` | | `LLM returned non-JSON response` | 尝试其他模型;一些小模型无法可靠地遵循 JSON 提示 | | 邮件未发送 | 检查 App Password;确保 Gmail 已启用 2FA | | 未出现告警 | 使用 `--verbose` 标志;将测试文件放入监控文件夹中 | | 文件提示 `Access Denied` | DLP 尝试读取被锁定的文件;它将在下次修改时重试 | ## 隐私与安全说明 - LLM **完全通过** Ollama **在本地运行** —— 不会向外部服务器发送任何数据。 - 系统会读取文件,但从不修改或删除它们(隔离是未来的功能)。 - 邮件告警包含文件名和模式摘要,但**不**包含完整的文件内容。 - 日志文件存储在本地,并在达到 5 MB 时自动轮转。 ## 许可证 MIT — 可自由使用、修改和分发。
标签:AI风险缓解, Python, 安全规则引擎, 敏感数据检测, 数据防泄漏(DLP), 文件监控, 无后门, 本地大语言模型, 逆向工具