bhuvaneshsam/Windows-Service-Process-Monitoring-Agent

GitHub: bhuvaneshsam/Windows-Service-Process-Monitoring-Agent

一个基于 Python 的 Windows 进程与服务安全监控代理,通过规则引擎检测可疑进程树、异常服务和高风险行为,辅助蓝队进行终端安全审计与应急响应。

Stars: 0 | Forks: 0

# Windows 服务与进程监控代理 ## 目录 1. [项目概述](#1-project-overview) 2. [架构与工作原理](#2-architecture--how-it-works) 3. [项目结构](#3-project-structure) 4. [检测能力](#4-detection-capabilities) 5. [安装](#5-installation) 6. [配置](#6-configuration) 7. [使用说明](#7-usage) 8. [示例输出](#8-sample-output) 9. [模块参考](#9-module-reference) 10. [检测规则详解](#10-detection-rules-explained) 11. [扩展代理](#11-extending-the-agent) 12. [故障排除](#12-troubleshooting) ## 1. 项目概述 Windows 服务和进程是最常见的攻击面,常被用于: - **恶意软件持久化** — 注册一个在开机时启动的恶意服务 - **权限提升** — 以 SYSTEM 权限运行且位于可写入路径的服务 - **进程注入** — 受信任的父进程派生出可疑的子进程 - **伪装** — 将恶意二进制文件命名为 `svchost.exe` 并从 `Temp\` 运行 该代理持续(或按需)分析正在运行的进程和服务, 将它们与可配置的白名单/黑名单及行为规则进行比较, 并生成带有颜色的控制台警报以及结构化的日志/报告文件。 ### 检测内容 | 威胁 | 技术 | |--------|-----------| | `winword.exe` 派生 `powershell.exe` | 可疑的父-子进程规则 | | 从 `%TEMP%` 或 `AppData` 运行的服务 | 基于路径的启发式检测 | | 不在已知服务列表中的未知服务 | 基线比较 | | 在 `System32` 之外运行的 `svchost.exe` | 伪装检测 | | 黑名单中的进程 | 名称匹配 | | 来自 `Downloads\` 的新进程 | 目录启发式检测 | ## 2. 架构与工作原理 ``` START │ ▼ ┌─────────────────────────────────┐ │ agent.py (Entry Point) │ │ Parses args, loads config, │ │ orchestrates all modules │ └────────────┬────────────────────┘ │ ┌────────┴────────┐ │ │ ▼ ▼ ┌──────────────┐ ┌──────────────────┐ │ ProcessMonitor│ │ ServiceAuditor │ │ │ │ │ │ • Enumerate │ │ • Enumerate all │ │ all procs │ │ Windows svcs │ │ • Build tree │ │ • Detect path │ │ • Detect │ │ anomalies │ │ bad pairs │ │ • Flag unknowns │ └──────┬───────┘ └────────┬─────────┘ │ │ ▼ │ ┌──────────────────┐ │ │ UnauthorizedDet. │ │ │ │ │ │ • Blacklist hit │ │ │ • Suspicious dir │ │ │ • Not whitelisted│ │ │ • Masquerading │ │ │ • High CPU/Mem │ │ └──────┬───────────┘ │ │ │ └─────────┬──────────┘ │ ▼ ┌─────────────────┐ │ AlertEngine │ │ │ │ • Aggregate all │ │ anomalies │ │ • Assign severity│ │ • Display to TTY │ └────────┬────────┘ │ ▼ ┌────────────┐ │ Reporter │ │ │ │ • JSON log │ │ • TXT report│ └────────────┘ │ ▼ END ``` ### 数据流 1. **枚举** — `psutil`(或 Windows 上的 WMI)读取所有实时进程和服务 2. **构建树** — 进程通过 PID → PPID 进行映射,以形成父-子树 3. **分析** — 每个模块独立运行其检测规则 4. **警报** — `AlertEngine` 合并所有异常,按严重程度排序并打印 5. **报告** — `Reporter` 写入 `log_.json` 和 `report_.txt` ## 3. 项目结构 ``` windows_monitor/ │ ├── agent.py # Main entry point — run this ├── config.py # Configuration loader (reads config.yaml) ├── config.yaml # Your customisable detection rules ├── requirements.txt # Python dependencies │ ├── modules/ │ ├── __init__.py │ ├── process_monitor.py # Process enumeration & parent-child detection │ ├── service_auditor.py # Service enumeration & audit │ ├── unauthorized_detector.py# Whitelist/blacklist & heuristic checks │ ├── alert_engine.py # Aggregates anomalies into alerts │ └── reporter.py # Writes JSON logs and text reports │ └── reports/ # Auto-created on first run ├── log_.json └── report_.txt ``` ## 4. 检测能力 ### A. 可疑的父-子进程关系 恶意软件经常滥用受信任的应用程序来派生 Shell。 | 合法父进程 | 可疑子进程 | 为什么是恶意行为 | |-------------------|-----------------|--------------| | `winword.exe` | `powershell.exe` | 基于 Macro 的恶意软件启动 Shell | | `excel.exe` | `cmd.exe` | 电子表格执行系统命令 | | `outlook.exe` | `wscript.exe` | 电子邮件附件运行 VBScript | | `lsass.exe` | `cmd.exe` | 凭据转储的副作用 | | `svchost.exe` | `powershell.exe` | 被注入的服务执行 Payload | | `iexplore.exe` | `mshta.exe` | 基于浏览器的 HTA 执行 | ### B. 服务异常检测 | 规则 | 严重性 | 描述 | |------|----------|-------------| | `SERVICE_SUSPICIOUS_PATH` | HIGH | 服务二进制文件位于 Temp/AppData/Downloads | | `SERVICE_PRIVILEGE_RISK` | HIGH | SYSTEM 账户服务位于可写入路径 | | `SERVICE_UNKNOWN` | MEDIUM | 服务名不在已知服务列表中 | ### C. 未授权进程检测 | 规则 | 严重性 | 触发条件 | |------|----------|---------| | 黑名单匹配 | HIGH | 进程名与配置中的 `blacklist` 匹配 | | 可疑目录 | HIGH | 可执行路径包含 `\Temp\`、`\Downloads\` 等 | | 伪装 | HIGH | 已知的系统名称(如 `svchost.exe`)从错误路径运行 | | 未在白名单中 | MEDIUM | 名称不在白名单中且不在系统路径中 | | 高 CPU | MEDIUM | CPU 使用率 ≥ 阈值(默认 90%) | | 高内存 | LOW | 内存 ≥ 阈值(默认 500 MB) | ## 5. 安装说明 ### 前置条件 | 需求 | 版本 | |-------------|---------| | Python | 3.8+ | | pip | 任意最新版本 | | Windows | 10/11 / Server 2016+(用于获取实时数据) | ### 步骤 1 — 克隆或下载 ``` # 如果使用 git: git clone https://github.com/your-org/windows-monitor.git cd windows-monitor # 或者直接复制该文件夹并 cd 进入该目录。 ``` ### 步骤 2 — 创建虚拟环境(推荐) ``` python -m venv venv # Windows: venv\Scripts\activate # Linux/macOS: source venv/bin/activate ``` ### 步骤 3 — 安装依赖 ``` pip install -r requirements.txt ``` **在 Windows 上**,还需安装 Windows 专属的可选包以获取完整的实时数据: ``` pip install pywin32 wmi ``` ### 步骤 4 — 验证安装 ``` python agent.py --help ``` 你应该会看到: ``` usage: agent.py [-h] [--output OUTPUT] [--config CONFIG] [--mode {full,process,service,unauthorized}] ``` ## 6. 配置 所有检测规则位于 `config.yaml` 中。请对其进行编辑以适配您的环境。 ### 白名单 始终被视为安全(永远不会被标记为“未知”)的进程: ``` whitelist: - explorer.exe - chrome.exe - mycompany_app.exe # Add your internal apps here ``` ### 黑名单 无论路径如何,始终被标记为 **HIGH** 的进程: ``` blacklist: - mimikatz.exe - nc.exe - my_pentest_tool.exe # Add tools you never want on prod ``` ### 可疑父-子进程规则 以 `parent: [list of bad children]` 格式添加条目: ``` suspicious_parent_child: winword.exe: - cmd.exe - powershell.exe myapp.exe: # Add your own apps - cmd.exe ``` ### 可疑目录 被视为高风险的路径(不区分大小写,部分匹配): ``` suspicious_directories: - \temp\ - \downloads\ - \appdata\roaming\ - \myshared\ # Add network shares, etc. ``` ### 警报阈值 ``` alert_thresholds: high_cpu_percent: 90.0 # Flag processes using ≥90% CPU high_memory_mb: 500 # Flag processes using ≥500 MB RAM ``` ## 7. 使用说明 ### 全面扫描(推荐) 运行所有检测模块并导出日志和报告: ``` python agent.py ``` ### 自定义输出目录 ``` python agent.py --output C:\SecurityLogs\monitor ``` ### 自定义配置文件 ``` python agent.py --config my_custom_config.yaml ``` ### 定向扫描(单模块) ``` # 仅进程树 python agent.py --mode process # 仅服务审计 python agent.py --mode service # 仅未授权进程检查 python agent.py --mode unauthorized ``` ### 全部选项 ``` python agent.py [-h] [--output OUTPUT] Output folder (default: reports/) [--config CONFIG] Config YAML path (default: config.yaml) [--mode {full,process,service,unauthorized}] ``` ### 计划扫描(Windows 任务计划程序) 创建一个计划任务以每 15 分钟运行一次: ``` $action = New-ScheduledTaskAction -Execute "python" -Argument "C:\monitor\agent.py --output C:\monitor\reports" $trigger = New-ScheduledTaskTrigger -RepetitionInterval (New-TimeSpan -Minutes 15) -Once -At (Get-Date) Register-ScheduledTask -TaskName "WinMonitorAgent" -Action $action -Trigger $trigger -RunLevel Highest ``` ## 8. 示例输出 ### 控制台 ``` ╔══════════════════════════════════════════════════════════╗ ║ Windows Service & Process Monitoring Agent ║ ║ Blue Team Security Toolkit v1.0 ║ ╚══════════════════════════════════════════════════════════╝ [STEP 1] Enumerating active processes and building process tree... Found 15 processes | 2 parent-child anomalies [STEP 2] Auditing Windows startup services... Found 12 services | 4 suspicious entries [STEP 3] Detecting unauthorized and high-risk processes... Found 3 unauthorized/suspicious processes [STEP 4] Generating alerts... ────────────────────────────────────────────────────────── [HIGH ] #001 [PROCESS_TREE] Suspicious Parent-Child Relationship winword.exe → powershell.exe (PID 3201) [HIGH ] #002 [UNAUTHORIZED_PROCESS] Unauthorized Process: svchost.exe Process masquerading as system binary — running from Temp\ [MEDIUM] #003 [SERVICE_AUDIT] Unknown service: 'WindowsHelperSvc' → AppData\Roaming\helper.exe [STEP 5] Exporting detection report... Log → reports/log_20260508_101109.json Report → reports/report_20260508_101109.txt [✔] Scan complete. Alerts → HIGH: 5 | MEDIUM: 3 | LOW: 0 ``` ### JSON 日志 (`log_.json`) ``` { "scan_timestamp": "20260508_101109", "summary": { "total_processes": 15, "total_services": 12, "total_alerts": 8, "high_alerts": 5, "medium_alerts": 3, "low_alerts": 0 }, "alerts": [ { "id": 1, "category": "PROCESS_TREE", "severity": "HIGH", "title": "Suspicious Parent-Child Relationship", "description": "Suspicious child process: winword.exe → powershell.exe (PID 3201)", "timestamp": "2026-05-08 10:11:09" } ] } ``` ### 文本报告 (`report_.txt`) ``` ══════════════════════════════════════════════════════════════════════ PARENT-CHILD PROCESS ANOMALIES ══════════════════════════════════════════════════════════════════════ ── PARENT_CHILD ────────────────────────────────────────────────── • Severity : HIGH • Description: Suspicious child process: winword.exe → powershell.exe (PID 3201) • Parent PID : 3200 (winword.exe) • Child PID : 3201 (powershell.exe) • Child Path : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe ``` ## 9. 模块参考 ### `agent.py` 入口点。解析 CLI 参数,实例化所有模块,编排扫描 Pipeline。 ### `config.py` 加载 `config.yaml` 并暴露类型化属性: - `config.whitelist` → `List[str]` (已转换为小写) - `config.blacklist` → `List[str]` (已转换为小写) - `config.suspicious_parent_child` → `Dict[str, List[str]]` - `config.suspicious_directories` → `List[str]` - `config.known_services` → `List[str]` - `config.alert_thresholds` → `Dict[str, float]` ### `modules/process_monitor.py` | 方法 | 返回值 | 描述 | |--------|---------|-------------| | `enumerate_processes()` | `List[Dict]` | 实时(psutil)或模拟的进程列表 | | `build_process_tree(procs)` | `Dict[int, List]` | `{ppid: [children]}` 映射 | | `detect_anomalies(tree)` | `List[Dict]` | 可疑的父-子进程对 | 进程字典的键:`pid`, `ppid`, `name`, `path`, `cpu`, `mem_mb`, `username`, `create_time`, `status` ### `modules/service_auditor.py` | 方法 | 返回值 | 描述 | |--------|---------|-------------| | `enumerate_services()` | `List[Dict]` | 实时(win32/WMI)或模拟的服务列表 | | `detect_anomalies(services)` | `List[Dict]` | 路径、权限和未知服务标志 | 服务字典的键:`name`, `display`, `status`, `start_type`, `path`, `account` ### `modules/unauthorized_detector.py` | 方法 | 返回值 | 描述 | |--------|---------|-------------| | `detect(processes)` | `List[Dict]` | 所有被标记的进程及其 `severity` 和 `reason` | ### `modules/alert_engine.py` | 方法 | 返回值 | 描述 | |--------|---------|-------------| | `generate_alerts(...)` | `List[Dict]` | 合并并按严重程度排序的警报列表 | | `display_alerts(alerts)` | `None` | 带颜色的控制台输出 | ### `modules/reporter.py` | 方法 | 返回值 | 描述 | |--------|---------|-------------| | `write_log(...)` | `str` (路径) | JSON 事件日志 | | `write_report(...)` | `str` (路径) | 人类可读的文本报告 | ## 10. 检测规则详解 ### 为什么 `winword.exe → powershell.exe` 是可疑的 Microsoft Word 在正常使用中绝不需要启动 PowerShell。 这种模式是**恶意宏执行**的典型特征(例如 VBA 宏调用 `Shell "powershell -enc "`)。 ### 为什么位于 `%TEMP%` 的服务是可疑的 合法的 Windows 服务从 `System32`、`Program Files` 或专用的 安装文件夹运行。恶意软件将其自身释放到 Temp 中,因为该位置**无需管理员权限即可写入**且清除不规律。 ### 为什么来自错误路径的 `svchost.exe` 是可疑的 真实的 `svchost.exe` 始终位于 `C:\Windows\System32\`。 恶意软件将其自身命名为 `svchost.exe` 并从 `AppData\Local\Temp\` 运行, 以混入任务管理器中数十个合法的 `svchost.exe` 实例中。 ### 为什么位于可写入路径的 SYSTEM 级别服务是危险的 如果服务二进制路径**可由非管理员用户写入**,攻击者就可以替换 该二进制文件,并在下次服务启动时让其以 SYSTEM 权限运行——这是一种经典的 **未加引号的服务路径/弱权限权限提升**。 ## 11. 扩展代理 ### 向 `process_monitor.py` 添加新的检测规则 ``` # 示例:标记命令行中包含 "cryptominer" 的任何进程 def detect_cmdline_anomalies(self, processes): anomalies = [] for proc in processes: cmdline = proc.get('cmdline', '').lower() if 'xmrig' in cmdline or '--donate-level' in cmdline: anomalies.append({ "type": "CRYPTOMINER", "severity": "HIGH", "description": f"Possible crypto-miner detected: PID {proc['pid']}", ... }) return anomalies ``` ### 向 `reporter.py` 添加新的输出格式 ``` def write_csv(self, alerts): import csv path = os.path.join(self.output_dir, f"alerts_{self.timestamp}.csv") with open(path, 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=['id','severity','category','description','timestamp']) writer.writeheader() writer.writerows(alerts) return path ``` ### 与 SIEM / Splunk 集成 JSON 日志是结构化的,易于摄取。将您的 Splunk Forwarder 指向 `reports/` 目录,或者将每个警报 POST 到 Splunk HTTP Event Collector: ``` import requests, json def send_to_splunk(alert, hec_url, token): payload = {"event": alert, "sourcetype": "win_monitor"} requests.post(hec_url, json=payload, headers={"Authorization": f"Splunk {token}"}) ``` ## 12. 故障排除 ### `ModuleNotFoundError: No module named 'psutil'` ``` pip install psutil PyYAML ``` ### 在 Windows 上出现 `Access is denied` 错误 **以管理员身份**运行终端。许多进程属性(exe 路径、 用户名)需要提升的权限。 ``` # 右键点击 PowerShell → “以管理员身份运行”,然后: python agent.py ``` ### 代理运行但只显示模拟数据 发生这种情况的原因可能是: - 您在 Linux/macOS 上(符合预期——模拟模式专为开发/测试而设计) - 在 Windows 上未安装 `pywin32` → `pip install pywin32` ### 误报过多 在 `config.yaml` 中增加您的白名单: ``` whitelist: - mycompany_app.exe - internal_tool.exe ``` 或将合法的服务名称添加到 `known_services` 中: ``` known_services: - mycompanysvc - internalsvc ``` ### 未生成报告 检查输出目录是否可写入: ``` python agent.py --output ./my_reports ``` ## 许可证 MIT — 可免费用于教育和商业用途。请注明出处。 *为 Windows 服务与进程监控代理项目而构建 — 蓝队安全工程*
标签:Awesome, Conpot, DAST, EDR, OpenCanary, osquery, Python, Windows安全, 伪装检测, 可疑活动检测, 基线比对, 安全代理, 安全报告, 库, 应急响应, 恶意代码分类, 恶意软件分析, 持久化检测, 无后门, 日志生成, 服务监控, 权限提升检测, 端点检测与响应, 系统管理, 网络安全, 脆弱性评估, 脱壳工具, 请求响应过滤, 路径启发式, 运维安全, 进程注入检测, 逆向工具, 隐私保护, 黑白名单