BlockGuard 是一款 Windows 数据丢失防护 (DLP) 代理,可在进程级别拦截并控制文件访问。它确保只有授权进程(通过可执行文件路径、加密哈希、验证码签名和完整性级别识别)才能读取受保护文件。所有其他进程默认通过 NTFS ACL 在操作系统内核级别被拒绝访问。
BlockGuard 采用三层模块化架构:``` ┌─────────────────────────────────────────────────────────────────┐ │ BlockGuard.Agent (Windows Service) │ │ Orchestrates all layers │ ├───────────────────┬─────────────────────┬───────────────────────┤ │ Layer 1 │ Layer 2 │ Layer 3 │ │ MONITORING │ POLICY & IDENTITY │ PROTECTION │ │ │ │ │ │ • ETW Kernel │ • Process Identity │ • DPAPI Encryption │ │ File Trace │ Validator (6 │ • Structured Audit │ │ • ACL Enforcer │ checks) │ Logger (JSON) │ │ (deny-by- │ • Policy Evaluator │ │ │ default) │ (AND-logic │ │ │ │ rules) │ │ │ │ • Identity Cache │ │ │ │ (LRU + TTL) │ │ └───────────────────┴─────────────────────┴───────────────────────┘
---
## 🖥️ UI 管理界面
BlockGuard 包含一个 **WPF 桌面应用程序**,用于通过可视界面管理受保护的文件和文件夹 — 无需手动编辑 `appsettings.json`。
<p align="center">
<img src="https://assets.kitploit.com/production/public/readmes/12349/51a9b7894117382666d869cee59860a33698f666133bd23c6b6cd48b225d942c.png" alt="BlockGuard UI" width="640" />
</p>
### 功能特性
- **仪表板** — 保护状态概览(文件总数、文件夹、加密状态)
- **受保护文件** — 通过文件浏览器对话框添加/删除要保护免受 AI 访问的文件和文件夹
- **活动日志** — 所有配置更改的实时日志
- **设置** — 查看配置文件路径和代理信息
- **代理状态** — 显示 BlockGuard 代理服务是否正在运行的实时指示器
### 如何启动 UI```powershell
# From the project root
dotnet run --project src/BlockGuard.UI
注意: UI 会读取和写入 Agent 项目中的
appsettings.json。保存更改后,请重新启动 BlockGuard Agent 服务以使更改生效。
在运行 BlockGuard 之前,请确保您的 Windows 机器上已安装以下内容:
| 要求 | 最低版本 | 检查命令 |
|---|---|---|
winget install Microsoft.DotNet.SDK.9
## 🚀 快速入门
### 1. 克隆仓库```powershell
git clone [email protected]:m2l33k/BlockGuard.git
cd BlockGuard
dotnet restore BlockGuard.sln
### 3. 构建解决方案```powershell
dotnet build BlockGuard.sln --configuration Release
你应该看到:``` Build succeeded. 0 Warning(s) 0 Error(s)
### 4. 配置受保护路径和规则
编辑 `src/BlockGuard.Agent/appsettings.json` 以定义 **要保护哪些文件** 以及 **哪些进程是授权的**:```json
{
"BlockGuard": {
"ProtectedPaths": [
"C:\\Secrets\\ai-model-keys",
"C:\\Secrets\\api-credentials.json"
],
"AuthorizedProcesses": [
{
"RuleName": "AI-Model-Inference-Engine",
"ExecutablePath": "C:\\Program Files\\MyAI\\inference.exe",
"MinimumIntegrityLevel": "Medium",
"RequireSignature": false
}
]
}
}
dotnet run --project src/BlockGuard.Agent
---
## ⚙️ 配置
所有配置均位于 `src/BlockGuard.Agent/appsettings.json` 的 `"BlockGuard"` 部分中。
### 受保护的路径
一个需要保护的文件或目录数组。目录会递归保护所有文件。```json
"ProtectedPaths": [
"C:\\Secrets\\ai-model-keys",
"C:\\Secrets\\api-credentials.json",
"D:\\Confidential\\reports"
]
每条规则定义了进程必须满足的条件才能获得访问权限。所有非空字段必须匹配(与逻辑):
示例:基于路径的规则(适用于 AI 模型进程)```json { "RuleName": "AI-Model-Inference-Engine", "ExecutablePath": "C:\Program Files\MyAI\inference.exe", "ExpectedFileHash": null, "ExpectedSignerSubject": null, "MinimumIntegrityLevel": "Medium", "RequireSignature": false }
**示例:基于签名的规则(适用于任何已签名管理工具)**```json
{
"RuleName": "Signed-Management-Tool",
"ExecutablePath": null,
"ExpectedFileHash": null,
"ExpectedSignerSubject": "CN=Contoso Security",
"MinimumIntegrityLevel": "High",
"RequireSignature": true
}
示例:哈希固定规则(用于最大防篡改保护)```json { "RuleName": "Pinned-Data-Processor", "ExecutablePath": "C:\Tools\processor.exe", "ExpectedFileHash": "a1b2c3d4e5f67890abcdef1234567890abcdef1234567890abcdef1234567890", "ExpectedSignerSubject": null, "MinimumIntegrityLevel": "Medium", "RequireSignature": false }
### 其他选项
| 选项 | 默认值 | 描述 |
|---|---|---|
| `IdentityCacheTtlSeconds` | `30` | 已验证进程标识的缓存持续时间(秒) |
| `HandleTimeoutSeconds` | `60` | 临时 ACL 授权的最大持续时间(秒) |
| `AuditLogPath` | `C:\ProgramData\BlockGuard\Logs\audit.json` | JSON 审计日志文件的路径 |
| `EnableDpapiEncryption` | `true` | 使用 DPAPI 对受保护文件进行静态加密 |
| `DpapiScope` | `LocalMachine` | DPAPI 范围:`LocalMachine` 或 `CurrentUser` |
---
## 🏃 运行代理
### 选项 A:开发模式(控制台)
最适合测试和调试。在 **提升的(管理员)PowerShell** 中运行:```powershell
dotnet run --project src/BlockGuard.Agent --configuration Release
[03:15:22 INF] [BlockGuard.Monitoring.AclEnforcer] Locked down file 'C:\Secrets\api-credentials.json' [03:15:22 INF] [BlockGuard.Protection.DpapiWrapper] Encrypted file 'C:\Secrets\api-credentials.json' [03:15:22 INF] [BlockGuard.Monitoring.EtwFileTraceSession] ETW file trace session started successfully. [03:15:22 INF] [BlockGuard.Agent.BlockGuardService] BlockGuard is now actively protecting 2 path(s).
按 `Ctrl+C` 停止。
### 选项 B:安装为 Windows 服务(生产环境)```powershell
# 1. Publish a self-contained build
dotnet publish src/BlockGuard.Agent -c Release -r win-x64 --self-contained -o C:\BlockGuard
# 2. Create the Windows Service
sc.exe create BlockGuard binPath= "C:\BlockGuard\BlockGuard.Agent.exe" start= auto obj= "NT AUTHORITY\SYSTEM" DisplayName= "BlockGuard Security Agent"
# 3. Set the service description
sc.exe description BlockGuard "Process-based file access security agent (DLP)"
# 4. Start the service
sc.exe start BlockGuard
管理服务:```powershell
sc.exe query BlockGuard
sc.exe stop BlockGuard
sc.exe delete BlockGuard
---
## ✅ 验证功能是否正常
按以下步骤确认 BlockGuard 正确保护文件。
### 测试 1:构建验证```powershell
# From the project root directory
dotnet build BlockGuard.sln
# Expected: Build succeeded with 0 Error(s)
dotnet run --project src/BlockGuard.Agent
**✅ 预期输出:**
- `BlockGuard Security Agent Starting` 消息
- 无 `CRITICAL` 或 `FATAL` 错误
- `ETW file trace session started successfully`
- `BlockGuard is now actively protecting X path(s)`
**❌ 如果看到 `ETW session — insufficient privileges`:**
- 你没有以管理员身份运行。右键点击 PowerShell → “以管理员身份运行”
### 测试 3:ACL 锁定验证
代理启动后,验证受保护文件是否已被锁定:```powershell
# Create a test protected file
New-Item -Path "C:\Secrets" -ItemType Directory -Force
Set-Content -Path "C:\Secrets\api-credentials.json" -Value '{"api_key": "secret123"}'
# Start the agent (it will lock down the file)
dotnet run --project src/BlockGuard.Agent
# In ANOTHER non-admin terminal, try to read the file:
Get-Content "C:\Secrets\api-credentials.json"
# Expected: Access Denied error
icacls "C:\Secrets\api-credentials.json"
### 测试5:审计日志检查
在代理运行一段时间后,检查审计日志:```powershell
# View the last 10 audit entries
Get-Content "C:\ProgramData\BlockGuard\Logs\audit.json" | Select-Object -Last 10
预期输出(JSON行):```json {"type":"operational","timestamp":"2026-03-05T02:30:00Z","eventType":"AgentStart","message":"BlockGuard security agent starting."} {"type":"access_decision","timestamp":"2026-03-05T02:30:05Z","verdict":"deny","reason":"No authorization rule matched this process identity.","file":"C:\Secrets\api-credentials.json","processId":5678}
### 测试6:验证ETW事件捕获
打开第二个终端,并在代理运行时尝试访问受保护的文件:```powershell
# Terminal 1: Agent is running with console output
dotnet run --project src/BlockGuard.Agent
# Terminal 2: Try reading a protected file with notepad
notepad.exe "C:\Secrets\api-credentials.json"
在终端1中,你应该会看到类似如下的日志条目:``` [03:20:15 WRN] [AUDIT] DENIED access to 'C:\Secrets\api-credentials.json' by PID 9876 (C:\Windows\System32\notepad.exe). Reason: No authorization rule matched
### 测试 7:验证未授权访问被阻止(AI 模型)
当某个进程(例如未授权的 AI 模型)尝试读取受保护的文件夹或文件时,代理会立即拒绝该访问。AI 将收到严格的**拒绝访问**错误,并且该尝试会被记录:
<p align="center">
<img src="https://assets.kitploit.com/production/public/readmes/12349/d2a2e20c0fc60e8b3a5f614b0a53c6c7275b634e93b1ce0b9fe4440c38215fac.png" alt="未授权访问被拒绝" width="600" />
</p>
### 测试 8:验证 DPAPI 加密```powershell
# Check that the .enc file was created
Test-Path "C:\Secrets\api-credentials.json.enc"
# Expected: True
# Check that the original plaintext file was securely deleted
Test-Path "C:\Secrets\api-credentials.json"
# Expected: False (if EnableDpapiEncryption is true)
当代理正在运行时,手动添加一个未授权的ACL条目:```powershell
icacls "C:\Secrets\api-credentials.json.enc" /grant Users:R
### 测试10:验证日志目录```powershell
# Check both log locations
Get-ChildItem "C:\ProgramData\BlockGuard\Logs\"
# Expected files:
# audit.json (structured JSON audit log)
# blockguard-20260305.log (daily rolling application log)
BlockGuard/ ├── BlockGuard.sln # Solution file ├── README.md # This file ├── architecture_overview.md # Detailed architecture documentation ├── assets/ │ ├── Untitled.jpg # Project logo (Trusty mascot) │ └── blockguard_ui_mockup_*.png # UI mockup screenshot │ ├── src/ │ ├── BlockGuard.Core/ # Shared models, interfaces, configuration │ │ ├── Configuration/ │ │ │ └── BlockGuardOptions.cs # Strongly-typed config (paths, rules, timeouts) │ │ ├── Interfaces/ │ │ │ ├── IAclEnforcer.cs # ACL management contract │ │ │ ├── IAuditLogger.cs # Audit logging contract │ │ │ ├── IDpapiWrapper.cs # DPAPI encryption contract │ │ │ ├── IFileAccessMonitor.cs # ETW monitoring contract │ │ │ ├── IPolicyEvaluator.cs # Policy evaluation contract │ │ │ └── IProcessIdentityValidator.cs # Process identity contract │ │ └── Models/ │ │ ├── AccessDecision.cs # Verdict + reason + matched rule │ │ ├── FileAccessEvent.cs # ETW event: file, PID, operation │ │ └── ProcessIdentity.cs # Hash, signature, SID, integrity │ │ │ ├── BlockGuard.Monitoring/ # Layer 1: Monitoring & Interception │ │ ├── EtwFileTraceSession.cs # Real-time kernel file ETW consumer │ │ └── AclEnforcer.cs # NTFS ACL lockdown + temp grants │ │ │ ├── BlockGuard.Policy/ # Layer 2: Policy & Identity Engine │ │ ├── ProcessIdentityValidator.cs # 6-layer P/Invoke validation │ │ ├── PolicyEvaluator.cs # AND-logic rule matching │ │ └── IdentityCache.cs # Thread-safe LRU cache (TTL) │ │ │ ├── BlockGuard.Protection/ # Layer 3: Decryption & Handle Manager │ │ ├── DpapiWrapper.cs # DPAPI encrypt/decrypt + secure delete │ │ └── AuditLogger.cs # Structured JSON audit logging │ │ │ ├── BlockGuard.Agent/ # Windows Service entry point │ │ ├── Program.cs # DI container, Serilog, hosting │ │ ├── BlockGuardService.cs # Main orchestrator (5-phase startup) │ │ └── appsettings.json # Configuration file │ │ │ └── BlockGuard.UI/ # WPF Desktop Management Interface │ ├── App.xaml / App.xaml.cs # Application resources & dark theme │ ├── MainWindow.xaml / .cs # Main window with sidebar navigation │ ├── ViewModels/ │ │ └── MainViewModel.cs # MVVM ViewModel (commands, config I/O) │ └── Services/ │ └── ConfigurationService.cs # Reads/writes appsettings.json
---
## 🔬 工作原理
### 启动序列(5个阶段)```
Phase 1: ACL Lockdown
└─ Strip all permissions from protected files
└─ Grant access only to SYSTEM + Administrators
└─ Disable ACL inheritance
Phase 2: DPAPI Encryption (optional)
└─ Encrypt each protected file at rest
└─ Securely delete plaintext (overwrite with random data)
└─ Store ciphertext as .enc files
Phase 3: Event Subscription
└─ Register handler for file access events
Phase 4: ETW Monitoring
└─ Start kernel-level file trace session
└─ Filter events by protected paths
└─ Emit FileAccessEvent for each match
Phase 5: Integrity Check Loop
└─ Every 60 seconds, verify ACLs are intact
└─ Auto-remediate if tampering detected
┌─────────────┐ ┌───────────────┐ ┌──────────────────┐ │ Process │ │ ETW Kernel │ │ Policy │ │ reads file │────▶│ File Provider │────▶│ Evaluator │ └─────────────┘ └───────────────┘ └──────────────────┘ │ ┌────────┴────────┐ ▼ ▼ ┌──────────┐ ┌──────────┐ │ ALLOW │ │ DENY │ │ │ │ │ │ Grant │ │ ACL is │ │ temp ACL │ │ already │ │ (60s) │ │ blocking │ └──────────┘ └──────────┘ │ │ ▼ ▼ ┌────────────────────────────┐ │ Audit Logger (JSON) │ └────────────────────────────┘
### 进程验证(6 项检查)
当进程访问受保护的文件时,BlockGuard 通过以下方式验证:
1. **可执行文件路径** — 解析并规范化完整路径(防止路径遍历)
2. **SHA-256 哈希** — 计算磁盘上二进制文件的哈希值(检测文件替换)
3. **Authenticode 签名** — 验证数字签名链(检测未签名/篡改的二进制文件)
4. **进程所有者 SID** — 查询令牌以识别运行账户
5. **完整性级别** — 读取强制标签(不可信/低/中/高/系统)
6. **父进程 ID** — 追踪进程创建链(检测注入)
所有检查均为**故障时关闭**:如果任何验证步骤失败,访问将被**拒绝**。
---
## 🛠️ 故障排除
### "ETW 会话 — 权限不足"
**原因:** 代理未以管理员/SYSTEM 权限运行。
**修复:**```powershell
# Right-click PowerShell → "Run as Administrator"
dotnet run --project src/BlockGuard.Agent
原因: 代理无法在未提升权限的情况下更改文件权限。
修复: 与上述相同 — 以管理员身份运行。
原因: appsettings.json 中的路径在您的机器上不存在。
修复: 首先创建目录和文件:```powershell New-Item -Path "C:\Secrets\ai-model-keys" -ItemType Directory -Force Set-Content -Path "C:\Secrets\api-credentials.json" -Value '{"key":"value"}'
### 克隆后出现构建错误
**解决方法:** 还原 NuGet 包:```powershell
dotnet restore BlockGuard.sln
dotnet build BlockGuard.sln
原因: 之前的代理实例崩溃并遗留了一个僵尸ETW会话。这会被自动清理——这是一个警告,而非错误。
原因: 可能是配置错误。请检查日志文件:```powershell Get-Content "C:\ProgramData\BlockGuard\Logs\blockguard-*.log" | Select-Object -Last 50
---
## 🔒 安全注意事项
### 此代理程序所能做到的
- ✅ 通过 ACL 强制实施,防止未经授权的进程**读取**受保护文件
- ✅ 通过 ETW 实时**审计**所有文件访问尝试
- ✅ 使用 DPAPI 对**静止状态**的文件进行加密
- ✅ 检测并**自动修复** ACL 篡改
### 此代理程序不能做到的
- ❌ **阻止正在进行的文件读取** — 这是用户模式代理程序;真正的正在进行的阻止需要内核微过滤驱动程序
- ❌ **阻止内核级攻击** — 恶意内核驱动程序可以绕过 NTFS ACL
- ❌ **阻止管理员覆盖** — 管理员帐户可以删除 ACL(通过篡改检测缓解)
### 生产环境建议
1. **以 `NT AUTHORITY\SYSTEM` 身份运行** — 使用 Windows 服务,而不是控制台应用程序
2. **使用 Authenticode 证书对代理二进制文件进行签名**,以防止自行篡改
3. **在卷上启用 BitLocker**,以实现全盘加密(补充 DPAPI)
4. **将审计日志转发到 SIEM**,以便集中监控
5. **启用安全启动 + 驱动程序签名强制**,以防止内核级绕过
---
## 🤝 贡献指南
1. 复刻(Fork)该仓库
2. 创建功能分支:`git checkout -b feature/my-feature`
3. 提交更改:`git commit -m "Add my feature"`
4. 推送到分支:`git push origin feature/my-feature`
5. 打开拉取请求(Pull Request)
### 代码风格
- 遵循 C# 命名约定(公共成员使用 PascalCase)
- 为所有公共 API 添加 XML 文档注释
- 每个验证都必须**失败关闭**(出错时拒绝)
- 在 `finally` 块中显式释放所有本机句柄
- 使用后立即清零敏感内存缓冲区
---
## 📄 许可证
本项目采用 MIT 许可证授权。详情请参阅 [LICENSE](https://github.com/m2l33k/blockguard/blob/HEAD/LICENSE)。
---
<p align="center">
<b>基于安全优先原则为 Windows 文件保护而构建。</b>
<br/>
<sub>BlockGuard — 因为你的数据需要守卫,而不仅仅是一把锁。</sub>
</p>
| 功能特性 | 描述 |
|---|
| 默认拒绝 ACL | 代理启动时锁定受保护文件——仅保留 SYSTEM 和管理员访问权限 |
| 实时 ETW 监控 | 通过 Windows 事件跟踪捕获内核级别文件 I/O 事件 |
| 6层进程验证 | 可执行文件路径、SHA-256 哈希、验证码签名、所有者 SID、完整性级别、父进程链 |
| DPAPI 文件加密 | 受保护文件使用 Windows 数据保护 API 进行静态加密 |
| 临时访问自动撤销 | 授权进程获得有时间限制的 ACL 授权,到期自动撤销 |
| 篡改检测 | 定期完整性检查,检测并自动修复 ACL 修改 |
| 结构化审计日志 | 所有访问尝试的 JSON 审计跟踪(可对接 SIEM) |
| Windows 服务 | 以 Windows 后台服务形式运行,身份为 NT AUTHORITY\SYSTEM |
| Windows 10 / Server 2019 |
winver |
| .NET SDK | 9.0 | dotnet --version |
| 管理员权限 | 需要 | 以管理员身份运行终端 |
| 字段 | 类型 | 描述 |
|---|
RuleName | string | 此规则的人类可读名称(用于审计日志) |
ExecutablePath | string? | 授权可执行文件的完整路径(不区分大小写) |
ExpectedFileHash | string? | 可执行文件的 SHA-256 哈希(防篡改检测) |
ExpectedSignerSubject | string? | Authenticode 证书主题(例如 "CN=Contoso") |
MinimumIntegrityLevel | string | 最低 Windows 完整性级别:Untrusted、Low、Medium、High、System |
RequireSignature | bool | 如果为 true,则可执行文件必须具有有效的 Authenticode 签名 |
| # | 测试 | 检查方法 | 预期结果 |
|---|
| 1 | 构建 | dotnet build BlockGuard.sln | 0 个错误 |
| 2 | 代理启动 | dotnet run --project src/BlockGuard.Agent(以管理员身份运行) | 启动横幅,无 CRITICAL 错误 |
| 3 | ACL 锁定 | icacls <protected-file> | 仅系统 + 管理员 |
| 4 | 未授权访问被阻止 | 从非管理员终端读取受保护文件 | 访问被拒绝 |
| 5 | ETW 捕获 | 在代理运行时读取受保护文件 | 控制台中显示 DENIED 日志条目 |
| 6 | 审计日志 | Get-Content C:\ProgramData\BlockGuard\Logs\audit.json | 包含判决结果的 JSON 条目 |
| 7 | DPAPI 加密 | Test-Path <file>.enc | .enc 文件存在 |
| 8 | 篡改检测 | icacls <file> /grant Users:R 然后等待 60 秒 | 记录自动修复 |