Security Guidance 安全指导插件
Security Guidance 插件在编辑文件时自动检测潜在的安全问题,包括命令注入、XSS、不安全代码模式等,帮助开发者避免常见的安全漏洞。
概述
Security Guidance 是一个自动化安全检查插件,它通过 PreToolUse 钩子在文件编辑时自动扫描 10 种常见的安全问题模式。无需配置,安装即用。
核心特性
| 特性 | 说明 |
|---|---|
| 自动检测 | 文件编辑时自动触发安全检查 |
| 10 种模式 | 覆盖命令注入、XSS、反序列化等常见漏洞 |
| 会话级别 | 同一会话内相同警告只显示一次 |
| 无依赖 | 仅使用 Python 标准库 |
| Fail-safe | 检查失败不会阻止正常操作 |
检测的安全问题
graph TD
A[Security Guidance] --> B[命令注入]
A --> C[XSS 攻击]
A --> D[代码注入]
A --> E[不安全反序列化]
B --> B1[child_process.exec]
B --> B2[os.system]
B --> B3[GitHub Actions]
C --> C1[dangerouslySetInnerHTML]
C --> C2[document.write]
C --> C3[innerHTML]
D --> D1[eval]
D --> D2[new Function]
E --> E1[pickle]
style A fill:#e3f2fd安装与配置
插件安装
# 安装 security-guidance 插件
/plugin install security-guidance@claude-plugins-official目录结构
plugins/security-guidance/
├── .claude-plugin/
│ └── plugin.json
└── hooks/
├── hooks.json # 钩子配置
└── security_reminder_hook.py # 安全检查脚本配置文件 (plugin.json)
{
"name": "security-guidance",
"version": "1.0.0",
"description": "Security reminder hook that warns about potential security issues when editing files, including command injection, XSS, and unsafe code patterns",
"author": {
"name": "David Dworken",
"email": "dworken@anthropic.com"
}
}钩子配置 (hooks.json)
{
"description": "Security reminder hook that warns about potential security issues when editing files",
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"type": "command",
"command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py"
}
],
"matcher": "Edit|Write|MultiEdit"
}
]
}
}10 种安全检查规则
1. GitHub Actions 工作流
检测:.github/workflows/*.yml 或 .yaml 文件
风险:命令注入,不安全的环境变量使用
示例:
# ❌ 危险:直接使用不信任的输入
- run: echo "PR title: ${{ github.event.pull_request.title }}"
# ✅ 安全:使用环境变量包装
- run: echo "PR title: $PR_TITLE"
env:
PR_TITLE: ${{ github.event.pull_request.title }}警告消息:
⚠️ GitHub Actions Workflow Security
Editing a GitHub Actions workflow file. Be careful of:
- Command injection via untrusted inputs
- Using environment variables to wrap untrusted inputs
See: https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions2. child_process.exec
检测:child_process.exec、exec()、execSync()
风险:命令注入漏洞
示例:
// ❌ 危险:用户输入直接拼接命令
const exec = require('child_process').exec;
exec(`ls ${userInput}`); // 可被注入!
// ✅ 安全:使用 execFile
const { execFile } = require('child_process');
execFile('ls', [userInput]);警告消息:
⚠️ Command Injection Risk
Using child_process.exec can lead to command injection vulnerabilities.
Consider using:
- execFile (arguments as array)
- execFileNoThrow tool3. new Function
检测:new Function 动态字符串
风险:代码注入漏洞
示例:
// ❌ 危险:动态代码执行
const fn = new Function('return ' + userInput);
// ✅ 安全:使用安全的替代方案
const result = JSON.parse(userInput); // 如果是 JSON警告消息:
⚠️ Dynamic Code Execution
Using 'new Function' with dynamic strings can lead to code injection.
Avoid dynamic code execution when possible.4. eval()
检测:eval() 调用
风险:重大安全风险,任意代码执行
示例:
// ❌ 极度危险
eval(userInput);
// ✅ 安全替代
JSON.parse(userInput); // 解析 JSON警告消息:
⚠️ Eval Security Risk
Using eval() is a significant security risk.
Consider using:
- JSON.parse() for JSON data
- Alternative design patterns5. React dangerouslySetInnerHTML
检测:dangerouslySetInnerHTML 使用
风险:XSS(跨站脚本攻击)
示例:
// ❌ 危险:未经清理的 HTML
<div dangerouslySetInnerHTML={{__html: userContent}} />
// ✅ 安全:使用 DOMPurify 清理
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(userContent)}} />警告消息:
⚠️ XSS Risk: dangerouslySetInnerHTML
Using dangerouslySetInnerHTML can lead to XSS vulnerabilities.
Ensure you:
- Use DOMPurify or similar library to sanitize HTML
- Never use with untrusted content6. document.write
检测:document.write() 调用
风险:XSS 和性能问题
示例:
// ❌ 危险
document.write('<script src="' + url + '"></script>');
// ✅ 安全
const script = document.createElement('script');
script.src = url;
document.body.appendChild(script);警告消息:
⚠️ XSS Risk: document.write
Using document.write can lead to XSS vulnerabilities and performance issues.
Use DOM methods instead:
- document.createElement()
- element.appendChild()7. innerHTML
检测:.innerHTML = 或 .innerHTML=
风险:XSS 攻击
示例:
// ❌ 危险:不信任的内容
element.innerHTML = userContent;
// ✅ 安全:使用 textContent 或清理
element.textContent = userContent;
// 或
element.innerHTML = DOMPurify.sanitize(userContent);警告消息:
⚠️ XSS Risk: innerHTML
Setting innerHTML with untrusted content can lead to XSS.
Consider:
- Using textContent for plain text
- Using DOMPurify for HTML sanitization8. Python pickle
检测:import pickle 或 from pickle import
风险:不信任数据的反序列化可导致任意代码执行
示例:
# ❌ 危险:反序列化不信任的数据
import pickle
data = pickle.loads(untrusted_data) # 可执行任意代码!
# ✅ 安全:使用 JSON
import json
data = json.loads(untrusted_data)警告消息:
⚠️ Pickle Security Risk
Using pickle with untrusted data can lead to arbitrary code execution.
Use safer alternatives:
- json for data serialization
- yaml.safe_load for YAML9. os.system
检测:os.system 或 from os import system
风险:命令注入
示例:
# ❌ 危险:用户输入拼接命令
import os
os.system(f"ls {user_input}") # 命令注入!
# ✅ 安全:使用 subprocess 和列表参数
import subprocess
subprocess.run(["ls", user_input])警告消息:
⚠️ Command Injection Risk: os.system
Using os.system with user input can lead to command injection.
Use subprocess module with list arguments:
- subprocess.run(["cmd", "arg"])
- subprocess.Popen(["cmd", "arg"])10. 通用模式
除了以上具体检测,插件还会对以下模式发出警告:
| 模式 | 风险 |
|---|---|
| 硬编码密码 | 凭证泄露 |
| 不安全的随机数 | 可预测的令牌 |
| SQL 字符串拼接 | SQL 注入 |
| 明文 HTTP | 中间人攻击 |
工作原理
检查流程
sequenceDiagram
participant U as 用户/Claude
participant H as PreToolUse Hook
participant S as security_reminder_hook.py
participant F as 状态文件
U->>H: 触发 Edit/Write/MultiEdit
H->>S: 传递工具参数
S->>S: 解析文件路径和内容
S->>S: 运行 10 种安全检查
alt 发现安全问题
S->>F: 检查是否已显示过
alt 未显示过
S->>F: 记录已显示
S->>U: 显示安全警告
else 已显示过
S->>S: 跳过(避免重复)
end
end
S->>H: 返回(允许操作继续)会话状态管理
状态文件位置:~/.claude/security_warnings_state_{session_id}.json
功能:
- 记录每个会话已显示的警告
- 避免同一问题重复警告
- 30 天后自动清理旧状态文件
错误处理
try:
# 执行安全检查
check_security_patterns(file_path, content)
except Exception as e:
# 记录错误但不阻止操作
log_error(e)
sys.exit(0) # 允许操作继续使用示例
示例 1:编辑 React 组件
当你编辑一个使用 dangerouslySetInnerHTML 的 React 组件时:
// 正在编辑 src/components/Content.jsx
function Content({ html }) {
return <div dangerouslySetInnerHTML={{__html: html}} />;
}触发的警告:
⚠️ XSS Risk: dangerouslySetInnerHTML
Using dangerouslySetInnerHTML can lead to XSS vulnerabilities.
Ensure you:
- Use DOMPurify or similar library to sanitize HTML
- Never use with untrusted content
See: https://owasp.org/www-community/attacks/xss/示例 2:编辑 Python 脚本
当你添加 os.system 调用时:
# 正在编辑 scripts/backup.py
import os
os.system(f"tar -czf backup.tar.gz {folder}")触发的警告:
⚠️ Command Injection Risk: os.system
Using os.system with user input can lead to command injection.
Use subprocess module with list arguments:
- subprocess.run(["cmd", "arg"])
- subprocess.Popen(["cmd", "arg"])
See: https://docs.python.org/3/library/subprocess.html示例 3:编辑 GitHub Actions
当你编辑工作流文件时:
# 正在编辑 .github/workflows/ci.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- run: echo ${{ github.event.issue.title }}触发的警告:
⚠️ GitHub Actions Workflow Security
Editing a GitHub Actions workflow file. Be careful of:
- Command injection via untrusted inputs (${{ }})
- Using environment variables to wrap untrusted inputs
See: https://securitylab.github.com/research/github-actions-untrusted-input/配置选项
环境变量
| 变量 | 说明 | 默认值 |
|---|---|---|
ENABLE_SECURITY_REMINDER | 启用/禁用安全提醒 | true |
# 临时禁用安全检查
export ENABLE_SECURITY_REMINDER=false自定义检查
如需添加自定义安全检查,可以修改 security_reminder_hook.py:
# 添加新的检查规则
SECURITY_PATTERNS = [
# ... 现有规则 ...
{
"name": "my_custom_check",
"pattern": r"my_dangerous_pattern",
"message": "Custom security warning",
"check_type": "content" # 或 "path"
}
]最佳实践
处理安全警告
| 警告类型 | 建议行动 |
|---|---|
| 命令注入 | 使用参数化命令,避免字符串拼接 |
| XSS | 使用 DOMPurify 或 textContent |
| eval/Function | 重新设计,避免动态代码执行 |
| pickle | 改用 JSON 或其他安全格式 |
| GitHub Actions | 使用环境变量包装输入 |
安全编码习惯
graph TD
A[编写代码] --> B{涉及用户输入?}
B -->|是| C[验证和清理]
B -->|否| D[继续]
C --> E{涉及命令执行?}
E -->|是| F[使用参数化 API]
E -->|否| G{涉及 HTML?}
G -->|是| H[使用 DOMPurify]
G -->|否| I{涉及序列化?}
I -->|是| J[使用 JSON]
I -->|否| D
F --> D
H --> D
J --> D
style C fill:#fff3e0
style F fill:#c8e6c9
style H fill:#c8e6c9
style J fill:#c8e6c9常见问题
Q: 警告太多了,如何减少?
A:
- 修复代码中的安全问题(最佳)
- 同一问题在会话中只警告一次
- 如确实需要,可通过环境变量禁用
Q: 为什么有些问题没有被检测到?
A: 插件使用模式匹配,可能遗漏:
- 变量名不同的情况
- 间接调用
- 复杂的代码结构
建议结合专业的安全扫描工具使用。
Q: 可以阻止而不是警告吗?
A: 当前版本只提供警告。如需阻止,可以使用 Hookify 插件创建自定义规则。
Q: 支持哪些编程语言?
A: 主要支持:
- JavaScript/TypeScript
- Python
- YAML (GitHub Actions)
其他语言的支持有限。
总结
Security Guidance 插件提供自动化的安全检查:
- 10 种检查 - 覆盖常见安全漏洞
- 自动触发 - 编辑文件时自动检查
- 智能去重 - 同一问题只警告一次
- 无干扰 - 不阻止操作,仅提供指导
帮助开发者在编码过程中及时发现和修复安全问题。
参考资源
- GitHub 源码 - 官方插件仓库
- OWASP Top 10 - 安全漏洞参考
- GitHub Actions 安全指南 - GitHub 官方文档
本文档基于 security-guidance 插件 v1.0.0 编写