Skip to main content

Multi-layer security analysis engine for AI agents

Project description

AgentMoss

AgentMoss 是一个可被任意 AI Agent 调用的独立通用安全分析服务。基于 OS Profile 机制,自动适配 Linux/Windows 的 syscall 检测模式,提供三层防御安全分析(启发式 → 逻辑规则 → LLM 语义分析)。

v2 更新:新增 OS Profile 系统(Linux/Windows 自适应)、两级快速放行白名单、rm 命令分级检测、脚本内容预扫描、LLM 结果缓存、Provider 自动识别与 Header 注入、fail-closed 安全原则。

目录

架构

┌─────────────────────────────────────────────────────┐
│          调用入口 (HTTP / Unix Socket / Hook)         │
│  POST /api/v1/analyze                                │
│  GET  /api/v1/health                                 │
├─────────────────────────────────────────────────────┤
│               ObservableAdapter                       │
│  AgentOS 可观测服务 syscall → 标准格式               │
├─────────────────────────────────────────────────────┤
│                OS Profile 选择                        │
│     ┌──────────┐    ┌──────────┐                     │
│     │  Linux   │    │ Windows  │                     │
│     │ Profile  │    │ Profile  │                     │
│     └──────────┘    └──────────┘                     │
├─────────────────────────────────────────────────────┤
│          两级快速放行白名单                            │
│  完全安全 (ls/pwd/echo...) → 跳过 L2+L3              │
│  只读敏感 (cat/grep/head...) → 跳过 L3,保留 L2      │
├─────────────────────────────────────────────────────┤
│          安全分析引擎 (三层防御)                       │
│                                                      │
│  层1: 启发式静态检测 (<1ms)                           │
│    ├── 用户自定义规则匹配                             │
│    ├── 危险命令正则 (30+ 模式,rm 分级检测)           │
│    └── Prompt 注入检测 (62 个中英关键词,9 类)         │
│                                                      │
│  层2: 逻辑规则检测 (<1ms)                             │
│    ├── Rule 1: read-before-write 原则                 │
│    ├── Rule 2: 意图偏离检测                           │
│    ├── Rule 3: 敏感路径访问 (19 条路径,分级风险)      │
│    ├── Rule 4: 危险操作模式 (通配符删除/重定向覆盖)    │
│    ├── Rule 5: 提权检测 (sudo/su/chmod u+s)          │
│    └── Rule 6: 横向移动检测 (ssh/scp/rsync)           │
│                                                      │
│  层3: LLM + Skill 深度分析 (2-5s)                    │
│    ├── 脚本内容预扫描 (18 个可疑模式,4 组合风险)      │
│    ├── Skill 规则匹配 (12 个 Skill,关键词加权评分)    │
│    ├── LLM 结果缓存 (200 条 FIFO)                    │
│    ├── Provider 自动识别 (15+ Provider)               │
│    └── LLM 语义安全判断 (fail-closed)                 │
└─────────────────────────────────────────────────────┘

设计原则

  • 适配在 OS 层,不在 Agent 层 — 不同 Agent 最终都会调用操作系统的 syscall,这是确定性的
  • 标准化 I/O 契约 — 任何 Agent 遵循 API 格式即可接入,无需关心内部实现
  • fail-closed 安全原则 — LLM 调用失败时默认拒绝,不确定时拒绝
  • 两级快速放行 — 完全安全命令跳过 L2+L3,只读敏感命令跳过 L3,降低性能开销
  • rm 命令分级检测 — 根据 flag 危险度 + 目标路径敏感度分级,避免无 flag 的 rm /tmp/x 被误拦

快速开始

安装

Python (PyPI)

pip install agent-moss

TypeScript (npm)

npm install @kenhkl/agent-moss

如需从源码安装:

git clone git@gitcode.com:kenhkl/AgentMoss.git
cd AgentMoss

# Python 版
pip install -e .

# TypeScript 版
cd ts && npm install && npm run build

CLI 使用

# 生成输入模板 (v2: 含 os_type 和 cwd 字段)
agent-moss init -o input.json

# 运行安全分析
agent-moss analyze input.json

# 启动 HTTP 服务 (TCP)
agent-moss server --port 9090

# 启动 Unix Domain Socket 服务(同机部署推荐)
agent-moss server --mode socket --socket /var/run/agent_moss/agent_moss.sock

# 指定配置文件
agent-moss server --mode socket --config /etc/agent_moss/agent_moss.yaml

API 调用

HTTP TCP 方式:

curl -X POST http://127.0.0.1:9090/api/v1/analyze \
  -H 'Content-Type: application/json' \
  -d '{
    "session_id": "test-001",
    "prompt_session": "列出系统文件",
    "action_history": [],
    "a_next": {
      "action_type": "bash",
      "action_detail": "ls -la /tmp"
    },
    "reason": "查看临时目录",
    "os_type": "",
    "cwd": "/home/user"
  }'

Unix Domain Socket 方式(同机低延迟):

curl --unix-socket /var/run/agent_moss/agent_moss.sock \
  -X POST http://localhost/api/v1/analyze \
  -H 'Content-Type: application/json' \
  -d '{
    "session_id": "test-001",
    "a_next": {
      "action_type": "bash",
      "action_detail": "ls -la /tmp"
    }
  }'

响应示例 (Allow)

{
  "decision": "Allow",
  "risk_level": "low",
  "risk_type": "",
  "violated_layers": [],
  "confidence": 100,
  "analysis_duration_ms": 10.8
}

TypeScript / Node.js 调用

import { createApp } from '@kenhkl/agent-moss';

const app = createApp();
// 通过 Hono app.fetch 在 Node.js / Bun / Electron 中调用
// 或启动独立服务: npx agent-moss server --port 9090

也可以直接 HTTP 调用:

const resp = await fetch('http://127.0.0.1:9090/api/v1/analyze', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        session_id: 'sess-001',
        a_next: { action_type: 'bash', action_detail: 'ls -la' },
        os_type: 'linux',
        cwd: '/home/user',
    }),
});
const result = await resp.json();
// → { decision: 'Allow'|'Deny', risk_level: 'low'|'...', ... }

响应示例 (Deny)

{
  "decision": "Deny",
  "reason": "检测到递归强制删除关键路径 (rm -rf /...)",
  "risk_level": "critical",
  "risk_type": "script_execution",
  "violated_layers": ["1.1"],
  "confidence": 95,
  "analysis_duration_ms": 1.2
}

LLM 配置

AgentMoss 的三层防御中,层3(LLM 语义分析)是可选的。层1+层2 的静态规则可以独立运行。

启用 LLM

方式 1:环境变量(推荐)

export AGENT_MOSS_LLM_API_KEY="sk-your-key"
# 可选:自定义模型和 API 端点
export AGENT_MOSS_LLM_MODEL="glm-5.0"
export AGENT_MOSS_LLM_BASE_URL="https://api.nextapi.store/v1"

方式 2:YAML 配置文件

编辑 config/agent_moss.yaml

llm:
  provider: "zhipu"
  model: "glm-5.0"
  base_url: "https://api.nextapi.store/v1"
  api_key_env: "AGENT_MOSS_LLM_API_KEY"
  temperature: 0.1
  max_tokens: 4096

security:
  llm_analysis:
    enabled: true

禁用 LLM(仅静态规则)

export AGENT_MOSS_DISABLE_LLM=1

支持的 LLM Provider

Provider URL 匹配 Provider Hint 说明
OpenAI api.openai.com openai 默认模型
Anthropic anthropic.com claude / anthropic Claude 系列
Google generativelanguage.googleapis.com google / gemini Gemini 系列
DeepSeek api.deepseek.com deepseek DeepSeek 系列
智谱 (GLM) open.bigmodel.cn zhipu / glm-cn / bigmodel GLM / CogView
智谱 Coding Plan api.z.ai zai-coding-plan 智谱编程套餐
OpenRouter openrouter.ai openrouter 多模型中转
Groq api.groq.com groq 高速推理
Mistral api.mistral.ai mistral Mistral 系列
Together api.together.xyz together 开源模型聚合
xAI api.x.ai xai / xai-grok Grok 系列
MiniMax api.minimaxi.com minimax MiniMax 系列
GitCode api-ai.gitcode.com gitcode GitCode AI
Ollama :11434 ollama 本地模型
任意兼容 other / custom / local 任何 OpenAI 兼容 API

自动识别 Provider 后,OpenRouter 和 xAI 会注入特定 HTTP Header(Referer、Title),确保平台正确计费。

openEuler 部署

前提

  • openEuler 22.03 LTS+
  • Python 3.10+
  • root 权限

一键安装

sudo dnf install -y python3 python3-pip python3-devel
git clone <repo-url> agent_moss
cd agent_moss
sudo bash scripts/install.sh

配置 LLM(生产环境)

# 写入 API Key(文件权限 600)
echo "AGENT_MOSS_LLM_API_KEY=sk-your-key" | sudo tee /etc/agent_moss/agent_moss.env
sudo chmod 600 /etc/agent_moss/agent_moss.env

# 编辑 LLM model / base_url
sudo vim /etc/agent_moss/agent_moss.yaml

启动方式

# HTTP TCP 模式(默认,适合跨机/调试)
sudo systemctl enable --now agent_moss

# Unix Socket 模式(同机部署推荐,更低延迟)
# 编辑 /etc/agent_moss/agent_moss.yaml 中 server.mode: "socket"
# 或修改 /etc/systemd/system/agent_moss.service 中的 ExecStart

启动与验证

sudo systemctl enable --now agent_moss

# HTTP 模式验证
curl http://127.0.0.1:9090/api/v1/health
# {"status":"healthy","version":"0.2.0"}

# Socket 模式验证
curl --unix-socket /var/run/agent_moss/agent_moss.sock \
  http://localhost/api/v1/health

管理命令

命令 说明
systemctl start agent_moss 启动
systemctl stop agent_moss 停止
systemctl restart agent_moss 重启
systemctl status agent_moss 查看状态
journalctl -u agent_moss -f 查看日志
systemctl disable agent_moss 取消开机启动

防火墙(HTTP 模式需要)

sudo firewall-cmd --add-port=9090/tcp --permanent
sudo firewall-cmd --reload

API 参考

方法 路径 说明
GET /api/v1/health 健康检查
POST /api/v1/analyze 安全分析

POST /api/v1/analyze

请求体 (v2)

{
  "session_id": "会话ID (必填)",
  "prompt_session": "原始任务描述 (可选,用于注入检测)",
  "action_history": [{"action_type": "...", "action_detail": "..."}],
  "a_next": {
    "action_type": "bash",
    "action_detail": "cat /etc/passwd"
  },
  "reason": "执行理由 (可选)",
  "os_type": "",
  "cwd": "/home/user/project",
  "metadata": {"agent_id": "...", "sandbox_id": "..."}
}
字段 类型 必填 说明
session_id string 会话唯一标识
prompt_session string 原始任务描述(层1 注入检测会扫描此字段)
action_history array 历史动作序列
a_next.action_type string 动作类型 (bash/file_read/file_write 等)
a_next.action_detail string 命令/动作详情
reason string 执行理由
os_type string "linux" / "windows",留空自动检测
cwd string 当前工作目录
metadata object 扩展元数据

响应字段

字段 类型 说明
decision string Allow / Deny
reason string 决策原因
risk_level string low / medium / high / critical
risk_type string 风险类别 (file_access, script_execution, data_exfiltration, prompt_injection, privilege_escalation, lateral_movement, ...)
violated_layers array 触发的检测层,如 ["1", "2"]
violated_policy string 违反的具体条款 (Deny 时)
policy string Cerberus TOML 策略 (Allow 时)
confidence int 置信度 0-100
analysis_duration_ms float 分析耗时(毫秒)

配置

优先级:环境变量 > YAML 配置文件 > 内置默认值

环境变量

变量 说明 默认值
AGENT_MOSS_LLM_API_KEY LLM API Key 未设置
AGENT_MOSS_LLM_MODEL LLM 模型名称 gpt-4o (TS) / anthropic/claude-3.5-sonnet (Python)
AGENT_MOSS_LLM_BASE_URL LLM API 端点 https://api.openai.com/v1 (TS) / https://openrouter.ai/api/v1 (Python)
AGENT_MOSS_LLM_TEMPERATURE LLM 采样温度 0.1
AGENT_MOSS_LLM_MAX_TOKENS LLM 最大输出 token 数 4096
AGENT_MOSS_LLM_TIMEOUT LLM 超时(秒) 300
AGENT_MOSS_LLM_RETRIES LLM 调用重试次数 2(共 3 次尝试)
AGENT_MOSS_DISABLE_LLM 设为 1 禁用层3 LLM 未设置
AGENT_MOSS_DISABLE_HEURISTIC 设为 1 禁用层1 启发式 未设置
AGENT_MOSS_DISABLE_LOGIC_RULES 设为 1 禁用层2 逻辑规则 未设置
AGENT_MOSS_CUSTOM_RULES 自定义规则 JSON 数组 []
AGENT_MOSS_ENABLE_POLICY_GEN 启用 Policy 生成 未设置
AGENT_MOSS_CONFIG_PATH 配置文件路径 内置默认

配置文件

参考 config/agent_moss.yaml

自定义规则

通过 AGENT_MOSS_CUSTOM_RULES 环境变量注入自定义正则规则:

export AGENT_MOSS_CUSTOM_RULES='[
  {"pattern": "kubectl delete namespace", "action": "Deny", "severity": "critical"},
  {"pattern": "docker rm -f", "action": "Deny", "severity": "high"}
]'

配置模板

# OS Profile 自动选择
os_profile:
  type: ""         # 留空自动检测,可手动指定 linux / windows

# 服务调用模式
server:
  mode: "http"     # "http" (TCP) 或 "socket" (Unix Domain Socket)
  socket_path: "/var/run/agent_moss/agent_moss.sock"

项目结构

AgentMoss/
├── agent_moss/               # Python 实现 (v0.2.0, PyPI: agent-moss)
│   ├── __init__.py
│   ├── cli.py                # 命令行工具
│   ├── profiles/             # OS Profile 系统
│   │   ├── base.py           # OSProfile 抽象基类
│   │   ├── linux.py          # LinuxProfile (22 危险模式 + 62 注入关键词 + 19 敏感路径)
│   │   └── windows.py        # WindowsProfile
│   ├── engine/               # 安全分析引擎
│   │   ├── coordinator.py    # 三层协调器 + 两级快速放行
│   │   ├── heuristic.py      # 层1: 启发式检测 (3 个子检测器)
│   │   ├── logic_rules.py    # 层2: 逻辑规则检测 (6 条规则)
│   │   ├── llm_analyzer.py   # 层3: LLM + Skill 深度分析 (200 条缓存)
│   │   ├── script_analyzer.py # 脚本内容预扫描 (18 个可疑模式)
│   │   ├── skill_engine.py   # Skill 匹配引擎 (12 个 Skill)
│   │   └── types.py          # 类型定义
│   ├── infra/                # 基础设施
│   │   ├── config.py         # 配置管理 (YAML + 环境变量)
│   │   ├── llm_client.py     # LLM 客户端 (15+ Provider 自动识别)
│   │   ├── logging.py        # 结构化日志
│   │   ├── parsers.py        # LLM 响应解析器
│   │   ├── policy_cache.py   # 策略缓存 (内存 + 文件持久化)
│   │   └── prompt_templates.py # Prompt 模板加载
│   ├── server/               # HTTP API 服务层
│   │   ├── app.py            # FastAPI 应用
│   │   ├── routes.py         # API 路由
│   │   ├── models.py         # Pydantic 请求/响应模型
│   │   └── socket_server.py  # Unix Domain Socket
│   ├── adapters/             # 适配器层
│   │   └── observable.py     # AgentOS syscall 数据适配
│   ├── skills/               # 12 个安全 Skill 规则 (Markdown)
│   ├── templates/            # 3 个 Prompt 模板 + policy_mapping
│   └── rules/                # 用户自定义规则
│
├── ts/                       # TypeScript 实现 (v0.2.1, npm: @kenhkl/agent-moss)
│   ├── src/
│   │   ├── cli.ts            # CLI 入口 (init/analyze/server)
│   │   ├── config.ts         # 配置管理 (环境变量 + Provider 识别)
│   │   ├── models.ts         # Zod 数据模型
│   │   ├── routes.ts         # Hono API 路由
│   │   ├── server.ts         # Hono HTTP 服务
│   │   └── engine/           # 三层防御引擎
│   │       ├── coordinator.ts    # 三层协调器 + 两级快速放行
│   │       ├── heuristic.ts      # 层1: 启发式 (30 危险模式 + 56 注入关键词)
│   │       ├── logic-rules.ts    # 层2: 逻辑规则 (6 条规则 + 20 敏感路径)
│   │       ├── llm-analyzer.ts   # 层3: LLM 分析 (200 条缓存 + fail-closed)
│   │       ├── script-analyzer.ts # 脚本内容预扫描 (16 个可疑模式)
│   │       ├── skill-loader.ts   # Skill 加载与匹配 (12 个 Skill)
│   │       └── template-loader.ts # Prompt 模板加载
│   ├── package.json
│   └── tsup.config.ts
│
├── config/
│   └── agent_moss.yaml       # YAML 配置模板
├── docs/
│   ├── design.md             # 基础架构设计
│   └── ...
└── tests/
    ├── conftest.py           # 共享 fixtures
    ├── test_all_cases.py     # 全量测试 (48 个用例)
    └── cases/                # 测试用例 JSON

测试

# 前两层测试(不依赖 LLM)
python3 -m pytest tests/ -v --no-header

# 包含 LLM 层(需 API Key)
AGENT_MOSS_LLM_API_KEY="sk-xxx" python3 -m pytest tests/ -v

# 仅运行特定测试
python3 -m pytest tests/ -k "deny" -v
python3 -m pytest tests/ -k "profile" -v

# TypeScript 版
cd ts && npm run build

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agent_moss-0.3.1.tar.gz (74.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agent_moss-0.3.1-py3-none-any.whl (87.7 kB view details)

Uploaded Python 3

File details

Details for the file agent_moss-0.3.1.tar.gz.

File metadata

  • Download URL: agent_moss-0.3.1.tar.gz
  • Upload date:
  • Size: 74.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for agent_moss-0.3.1.tar.gz
Algorithm Hash digest
SHA256 b5f3ebcc21a3266b1b92c06e3f268a48876bc17a5e1811ced5f22147cf937c9b
MD5 4e3f65dd7516675572c2bdb5038da3c6
BLAKE2b-256 777038399f4d6495a8994ca1e4bc33584cd38992fc6c43c6ea570c3d27989ed4

See more details on using hashes here.

File details

Details for the file agent_moss-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: agent_moss-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 87.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for agent_moss-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 57f84c8b58ca6d38313db7d56fe2eec7d9d9c80d70d210100ffc73c4b823e234
MD5 9d8eb107c10df746d77da3631abf8885
BLAKE2b-256 1214a416ccc78b3f1bddcfd632ef8375e3eaad590fab008c072e260ea8c65393

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page