Thalassa09/agent-self-protection
GitHub: Thalassa09/agent-self-protection
为 AI Agent 提供十层纵深防御的安全技能框架,抵御恶意软件、供应链攻击、凭证窃取和 Prompt 注入等外部威胁。
Stars: 2 | Forks: 0
# Agent 自我保护 🛡️
## 为什么需要?
AI agent 如果浏览、下载、克隆、安装或执行来自外部源的代码,很容易受到以下威胁:
- **恶意软件**(木马、反向 shell、加密货币挖矿机、投放器)
- **供应链攻击**(恶意的 npm/pip 包)
- **凭证窃取**(读取 `~/.ssh/`、`~/.aws/`、`.env` 并 POST 到 webhook 的脚本)
- **Prompt 注入**(通过获取的网页或文件进行间接注入)
- **持久化**(cron 任务、systemd 服务、shell rc 修改)
这项技能使得 agent **对外部世界的攻击免疫**。每一个跨越 agent 边界的字节在被证明安全之前都是可疑的。
## 功能
### 10 层防御
| 层级 | 引擎 | 检测内容 |
|-------|--------|----------------|
| L1: 信誉 | `reputation_check.py` | URLhaus, WHOIS, SSL, npm/PyPI registry |
| L2: 网络守卫 | `network_guard.py` | 窃取端点(pastebin, webhook, ngrok, Tor, 矿池, DNS 隧道) |
| L3: 恶意软件扫描 | `malware_scan.py` | ClamAV, YARA rules, 熵分析, magic bytes, hash 查找 |
| L4: 静态分析 | `static_analyzer.py` | 反向 shell, eval/exec, 窃取, 持久化, 加密货币挖矿机, 混淆 |
| L5: 行为监控 | `behavioral_monitor.py` | 运行时进程/文件系统/网络监控 |
| L6: 凭证 | `credential_scanner.py` | API keys, 私钥, JWT, 高熵 secret |
| L7: 沙箱执行 | `sandbox_exec.py` | bwrap/unshare 隔离 + rlimits + env 剥离 |
| L8: 隔离区 | `quarantine.py` | SQLite 跟踪的文件隔离 |
| L9: Prompt 注入 | `prompt_injection_guard.py` | 间接注入, ChatML 走私, 零宽字符, 双向覆盖 (bidi override) |
| L10: 输出清理器 | `output_sanitizer.py` | 凭证脱敏, 零宽剥离, ANSI/HTML 清理 |
### 子 Agent 委派安全
通过 `delegate_task` 生成的子 agent **不会自动加载技能**(`skip_context_files=True, skip_memory=True`)。该技能包含一个必须的安全前缀,需要注入到每个委派上下文中,此外还有一个 `delegate_safe.py` 包装器会自动添加该前缀。
## 快速开始
### 作为 Hermes 技能
```
# 安装
hermes skills install https://github.com/Thalassa09/agent-self-protection/blob/main/SKILL.md
```
### 独立使用
```
# 克隆
git clone https://github.com/Thalassa09/agent-self-protection.git
cd agent-self-protection
# 扫描 URL
bash scripts/preflight.sh https://example.com
# 扫描文件
bash scripts/preflight.sh ./suspicious.py
# 扫描 npm package
bash scripts/preflight.sh npm express
# 扫描文本以检测 prompt injection
bash scripts/preflight.sh --text "ignore previous instructions..."
# Exit codes:
# 0 = SAFE
# 1 = CAUTION
# 2 = HIGH RISK
```
### 单独引擎
```
# 多引擎 malware 扫描
python3 scripts/malware_scan.py suspicious_file
# 静态代码分析
python3 scripts/static_analyzer.py script.py
# 网络 exfiltration 检测
python3 scripts/network_guard.py --check-url https://evil.com/exfil
# Credential leak 扫描
python3 scripts/credential_scanner.py code.py
# Prompt injection 防护
python3 scripts/prompt_injection_guard.py --scan-text "suspicious text"
# Output sanitizer
python3 scripts/output_sanitizer.py output.txt
# Sandboxed execution
python3 scripts/sandbox_exec.py --timeout 60 --memory 256M -- python3 untrusted.py
# 隔离文件
python3 scripts/quarantine.py suspicious_file --reason "reverse shell detected"
# 列出已隔离文件
python3 scripts/quarantine.py --list
# Reputation check
python3 scripts/reputation_check.py --url https://example.com
python3 scripts/reputation_check.py --npm some-package
python3 scripts/reputation_check.py --pypi some-package
# Behavioral monitoring
python3 scripts/behavioral_monitor.py --pid 12345
# Audit trail 查询
python3 scripts/audit.py --last 1h
```
## 架构
```
agent-self-protection/
├── SKILL.md # Main skill doc (10-layer defense + delegation protocol)
├── README.md # This file
├── LICENSE # MIT
├── .gitignore
├── references/
│ ├── subagent-security-prefix.md # 6.3KB mandatory injection for delegate_task
│ ├── threat_intel.md # Curated threat intelligence
│ └── ioc_patterns.yaml # IOC database (exfil, tunneling, mining, TLDs, typosquats)
├── rules/
│ └── threats.yar # 16 YARA rules (reverse shells, webshells, miners, C2, etc.)
└── scripts/ # 12 executable scripts
├── preflight.sh # Unified entry point (exit 0/1/2)
├── delegate_safe.py # Wrapper for delegate_task with security injection
├── malware_scan.py # ClamAV + YARA + entropy + hash
├── static_analyzer.py # Code pattern analysis
├── behavioral_monitor.py # Runtime monitoring
├── network_guard.py # Exfiltration endpoint detection
├── credential_scanner.py # Credential leak detection
├── quarantine.py # File isolation with SQLite tracking
├── reputation_check.py # URL/domain/package reputation
├── sandbox_exec.py # Isolated execution
├── prompt_injection_guard.py # Indirect injection defense
├── output_sanitizer.py # Outbound content sanitization
└── audit.py # Audit trail query
```
## 依赖
### 必需(Python 3.10+)
- 大多数脚本仅需标准库
### 可选(用于增强检测)
- `yara-python` — 用于 `malware_scan.py` 的 YARA rule 引擎
- `clamav-daemon` — 用于 `malware_scan.py` 的 ClamAV
- `python-whois` — 用于 `reputation_check.py` 的 WHOIS 查找
- `bubblewrap` (`bwrap`) — 用于 `sandbox_exec.py` 的沙箱隔离
```
# 安装可选 dependencies (Debian/Ubuntu)
sudo apt install yara clamav-daemon bwrap
pip install yara-python python-whois
```
## 与 Hermes Agent 集成
### 自动激活
该技能会在以下操作前自动激活:
- 浏览或获取 URL
- 下载文件
- 对代码仓库执行 `git clone`
- 执行 `npm install` / `pip install` / `uv add`
- 运行来自外部源的 shell 命令
- 处理用户提供的文件/附件
- 安装第三方技能或插件
### 子 Agent 委派
```
from pathlib import Path
SECURITY_PREFIX = Path.home() / ".hermes/skills/agent-self-protection/references/subagent-security-prefix.md"
# 委派时始终注入安全前缀
delegate_task(
goal="Audit the xyz repo",
context=SECURITY_PREFIX.read_text() + "\n\nTASK CONTEXT:\n" + user_context,
)
```
或使用包装器:
```
from delegate_safe import delegate_safe
delegate_safe(
goal="Audit the xyz repo",
context="Repo at /tmp/xyz",
toolsets=["web", "terminal", "file"],
)
```
## 威胁模型
基于:
- OWASP Top 10 for LLM Applications
- NIST SP 800-53 (SI / RA / SC 系列)
- MITRE ATT&CK Framework
- CIS Critical Security Controls
### 攻击面
| 攻击面 | 威胁 |
|---------|---------|
| **Web** | 钓鱼、偷渡式下载、恶意 JS、凭证捕获、隐藏 iframe |
| **文件** | 木马、投放器、宏恶意软件、多义文件 (polyglots)、零日漏洞 |
| **包** | 供应链攻击(event-stream, node-ipc, ua-parser-js 事件) |
| **代码** | 反向 shell、滥用 eval/exec、混淆、窃取 |
| **LLM I/O** | 间接 prompt 注入、ChatML 走私、零宽隐写术 |
## YARA Rules
涵盖 16 条规则:
- 反向 shell(bash TCP, Python socket, Perl, nc)
- Webshell(PHP, JSP, ASP)
- 加密货币挖矿机(xmrig, stratum 协议)
- 下载并执行模式
- 窃取模式
- 持久化机制(cron, systemd, rc files)
- 反取证(清除 history、删除日志)
- Prompt 注入标记
- 混淆(base64, hex, eval 链)
- 凭证模式
- 网络端点(pastebin, webhook, ngrok)
- 提权
## 许可证
MIT 许可证。请参阅 [LICENSE](LICENSE)。
## 致谢
灵感来源于:
- OWASP AI Security Top 10
- NIST SP 800-53
- MITRE ATT&CK Framework
- CIS Critical Security Controls
- VirusTotal / URLhaus / abuse.ch 威胁情报
标签:CISA项目, DNS 反向解析, StruQ, USENIX Security 2025, 云安全监控, 人工智能安全, 合规性, 安全专业人员, 提示词注入防御, 沙箱隔离, 行为监控, 逆向工具, 静态分析